标签:
1 # -*- coding: utf-8 -*- 2 from PyQt4.QtGui import * 3 from PyQt4.QtCore import * 4 import sys 5 QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8")) 6 7 class Settings(QDialog): 8 def __init__(self,parent=None): 9 super(Settings,self).__init__(parent) 10 self.setWindowTitle(self.tr("利用QDataStream对文件进行存取")) 11 12 self.label = QLabel(self.tr("通道:")) 13 self.channelSpinBox = QSpinBox() 14 self.channelSpinBox.setRange(0,20) 15 self.timeLabel = QLabel(self.tr("第一次运行")) 16 17 self.label_gong =QLabel(self.tr("功率:")) 18 self.powerComboBox = QComboBox() 19 self.powerComboBox.addItem(self.tr("大"),"大") 20 self.powerComboBox.addItem(self.tr("中"),"中") 21 self.powerComboBox.addItem(self.tr("小"),"小") 22 self.saveButton = QPushButton(self.tr("保存")) 23 24 self.label_Frequency = QLabel(self.tr("频率:")) 25 self.FrequencyEdit = QLineEdit() 26 self.getButton = QPushButton(self.tr("读取")) 27 28 layout = QGridLayout(self) 29 layout.addWidget(self.label,0,0) 30 layout.addWidget(self.channelSpinBox,0,1) 31 layout.addWidget(self.timeLabel,0,2) 32 33 layout.addWidget(self.label_gong,1,0) 34 layout.addWidget(self.powerComboBox,1,1) 35 layout.addWidget(self.saveButton,1,2) 36 37 layout.addWidget(self.label_Frequency,2,0) 38 layout.addWidget(self.FrequencyEdit,2,1) 39 layout.addWidget(self.getButton,2,2) 40 41 self.resize(250,150) 42 43 self.connect(self.saveButton,SIGNAL("clicked()"),self.slotSave) 44 self.connect(self.getButton,SIGNAL("clicked()"),self.slotGet) 45 46 def slotSave(self): 47 self.channel = self.channelSpinBox.value() 48 self.power = self.powerComboBox.currentIndex() 49 self.frequency = self.FrequencyEdit.text() 50 self.time = QDateTime() 51 file = QFile("parameters.dat") 52 file.open(QIODevice.WriteOnly) 53 out = QDataStream(file) 54 out.setVersion(QDataStream.Qt_4_0) 55 56 out.writeUInt32(0xa1a2a3a4) 57 out.writeUInt32(self.channel) 58 out.writeUInt32(self.power) 59 out.writeString(self.frequency) 60 out << self.time.currentDateTime() 61 62 def slotGet(self): 63 file = QFile("parameters.dat") 64 file.open(QIODevice.ReadOnly) 65 In = QDataStream(file) 66 In.setVersion(QDataStream.Qt_4_0) 67 magic = In.readUInt32() 68 if magic != 0xa1a2a3a4: 69 QMessageBox.information(self,"exception",self.tr("invalid file format")) 70 return 71 channel = In.readUInt32() 72 power = In.readUInt32() 73 frequency = In.readString() 74 time = QDateTime() 75 In >> time 76 self.channelSpinBox.setValue(channel) 77 self.powerComboBox.setCurrentIndex(power) 78 self.FrequencyEdit.setText(frequency) 79 lastTime = time.date().toString(Qt.ISODate) + " " + time.time().toString() 80 self.timeLabel.setText(lastTime) 81 82 app=QApplication(sys.argv) 83 dialog=Settings() 84 dialog.show() 85 app.exec_()
【转载】 Pyqt 利用QDataStream对文件进行存取
标签:
原文地址:http://www.cnblogs.com/dcb3688/p/4331622.html