Example #1
0
    def testCurvePlotItemArray2Path(self):
        size = 5
        x = np.arange(size)
        y = 2 * np.arange(size)
        item = CurvePlotItem(x, y)
        self._widget.addItem(item)
        p = item._graph

        # stream path
        arr = QByteArray()
        buf = QDataStream(arr, QIODevice.ReadWrite)
        buf << p
        buf.device().reset()

        # test protocol
        assert arr.size() == 4 + size * 20 + 8
        assert buf.readInt32() == size
        for i in range(5):
            if i == 0:
                assert buf.readInt32() == 0
            else:
                assert buf.readInt32() == 1
            assert buf.readDouble() == x[i]
            assert buf.readDouble() == y[i]
        assert buf.readInt32() == 0
        assert buf.readInt32() == 0
Example #2
0
 def load(self):
     exception = None
     fh = None
     try:
         if not self.filename:
             raise IOError("no filename specified for loading")
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(fh.errorString())
         stream = QDataStream(fh)
         magic = stream.readInt32()
         if magic != MAGIC_NUMBER:
             raise IOError("unrecognized file type")
         fileVersion = stream.readInt16()
         if fileVersion != FILE_VERSION:
             raise IOError("unrecognized file type version")
         self.ships = {}
         while not stream.atEnd():
             name = stream.readQString()
             owner = stream.readQString()
             country = stream.readQString()
             description = stream.readQString()
             teu = stream.readInt32()
             ship = Ship(name, owner, country, teu, description)
             self.ships[id(ship)] = ship
             self.owners.add(owner)
             self.countries.add(country)
         self.dirty = False
     except IOError as e:
         exception = e
     finally:
         if fh is not None:
             fh.close()
         if exception is not None:
             raise exception
Example #3
0
    def _decode_data(self, data):

        encoded_data = data.data(self.mime_format)
        stream = QDataStream(encoded_data)

        dragged_states = []
        dragged_state = []
        r_previous = None

        while not stream.atEnd():

            r = stream.readInt32()
            c = stream.readInt32()

            if r != (r_previous if r_previous else r):
                dragged_states.append(dragged_state)
                dragged_state.clear()
            r_previous = r

            num_items_in_map = stream.readUInt32()

            for i in range(num_items_in_map):
                key = stream.readInt32()
                value = QVariant()
                stream >> value
                dragged_state.append(value.value())

        dragged_states.append(dragged_state)

        return dragged_states
Example #4
0
    def getMsg(self):
        self.buffer.append(self.readAll())
        totalLen = self.buffer.size()
        while totalLen:
            in_ = QDataStream(self.buffer, QIODevice.ReadOnly)
            in_.setVersion(QDataStream.Qt_5_9)

            if self.msgLen == 0:
                if totalLen >= self.headLen:
                    self.msgLen = in_.readInt32()
                    if totalLen >= self.headLen + self.msgLen:
                        msg = ""
                        msg = in_.readQString()
                        self.getMsgSignal.emit(msg)
                        self.buffer = self.buffer.right(totalLen -
                                                        self.headLen -
                                                        self.msgLen - 4)
                        self.msgLen = 0
                        totalLen = self.buffer.size()
                    else:
                        break
                else:
                    break
            else:
                if totalLen >= self.headLen + self.msgLen:
                    in_.readInt32()
                    msg = ""
                    msg = in_.readQString()
                    self.getMsgSignal.emit(msg)
                    self.buffer = self.buffer.right(totalLen - self.headLen -
                                                    self.msgLen - 4)
                    self.msgLen = 0
                    totalLen = self.buffer.size()
                else:
                    break
Example #5
0
 def decodeMimeData(self, mimedata):
     data = []
     stream = QDataStream(mimedata.data(MyHeader.MimeType))
     while not stream.atEnd():
         row = stream.readInt32()
         column = stream.readInt32()
         item = {}
         for count in range(stream.readInt32()):
             key = stream.readInt32()
             item[key] = stream.readQVariant()
         data.append([item[Qt.UserRole], item[Qt.DisplayRole]])
     return data
Example #6
0
    def decodeData(self, encoded, tree):
        items = []
        rows = []
        stream = QDataStream(encoded, QIODevice.ReadOnly)
        
        _ = stream.readInt32()
        ind1 = stream.readInt32()
        ind2 = stream.readInt32()
        ind3 = stream.readInt32()
        
        #print('dencoded [' + str(ind1) + ', '+ str(ind2)+']')

        return [ind1, ind2, ind3]
Example #7
0
    def load_datastream(self, fname):
        error = None
        fh = None

        try:
            fh = QFile(fname)
            if not fh.open(QIODevice.ReadOnly):
                raise IOError(str(fh.errorString()))

            stream = QDataStream(fh)
            while not stream.atEnd():
                self.label = stream.readQString()
                self.diameter = stream.readInt32()
                self.top_elev = stream.readDouble()
                self.design_load = stream.readDouble()
        except EnvironmentError as e:
            error = "Failed to load:{0}".format(e)

        finally:
            if fh is not None:
                fh.close()
            if error is not None:
                print(error)
            self.__dirty = False
            print("load data from{0}".format(QFileInfo(fname).fileName()))


# 缺少计算参数的类
Example #8
0
    def decode_data(self, bytearray):

        data = {}

        ds = QDataStream(bytearray)
        while not ds.atEnd():

            row = ds.readInt32()
            column = ds.readInt32()

            map_items = ds.readInt32()
            for i in range(map_items):
                key = ds.readInt32()

                value = QVariant()
                ds >> value
                data[Qt.ItemDataRole(key)] = value

        return data
Example #9
0
def decode_data(bytearray):
    data = []
    ds = QDataStream(bytearray)
    while not ds.atEnd():
        item = {0: ''}
        row = ds.readInt32()
        column = ds.readInt32()

        map_items = ds.readInt32()

        for i in range(map_items):

            key = ds.readInt32()

            value = QVariant()
            ds >> value
            item[key] = value.value()
        data.append(item)
    return data
 def decodeMimeData(self, the_bytearray: QByteArray):
     """see:
     https://wiki.python.org/moin/PyQt/Handling%20Qt's%20internal%20item%20MIME%20type
     http://doc.qt.io/qt-5.5/datastreamformat.html
     """
     data = {}
     ds = QDataStream(the_bytearray)
     while not ds.atEnd():
         item = []
         row = ds.readInt32()
         column = ds.readInt32()
         number_of_items = ds.readInt32()
         # print("rc:", row, column, number_of_items)
         for i in range(number_of_items):
             key = ds.readInt32()
             value = QVariant()
             ds >> value
             item.append((value.value(), Qt.ItemDataRole(key)))
         data[(row, column)] = item
     return data
Example #11
0
 def decodeMimeData(self, the_bytearray: QByteArray):
     """see:
     https://wiki.python.org/moin/PyQt/Handling%20Qt's%20internal%20item%20MIME%20type
     http://doc.qt.io/qt-5.5/datastreamformat.html
     """
     data = {}
     ds = QDataStream(the_bytearray)
     while not ds.atEnd():
         item = []
         row = ds.readInt32()
         column = ds.readInt32()
         number_of_items = ds.readInt32()
         # print("rc:", row, column, number_of_items)
         for i in range(number_of_items):
             key = ds.readInt32()
             value = QVariant()
             ds >> value
             item.append((value.value(), Qt.ItemDataRole(key)))
         data[(row, column)] = item
     return data
Example #12
0
    def _decode_data(self, data):
        encoded_data = data.data(self.mime_format)
        stream = QDataStream(encoded_data)

        dragged_data = []

        while not stream.atEnd():
            row = stream.readInt32()
            column = stream.readInt32()

            num_items_in_map = stream.readUInt32()
            item = {'row': row, 'column': column, 'map items': {}}
            for i in range(num_items_in_map):
                key = stream.readInt32()
                value = QVariant()
                stream >> value
                item['map items'][Qt.ItemDataRole(key)] = value.value()

            dragged_data.append(item)

        return dragged_data
Example #13
0
def _list_item_mime_to_text(mime_data, c=False):
    if mime_data.hasText():
        return
    data = mime_data.data('application/x-qabstractitemmodeldatalist')
    if not data:
        return
    ds = QDataStream(data)
    ds.readInt32() # read row (don't need)
    ds.readInt32() # read col (don't need)
    value = None
    for i in range(ds.readInt32()):
        if Qt.ItemDataRole(ds.readInt32()) == Qt.DisplayRole:
            value = ds.readQVariant()
            break
    if value is None:
        return
    if c:
        value = 'c("{}")'.format(value)
    else:
        value = '"{}"'.format(value)
    mime_data.setText(value)
Example #14
0
    def dropMimeData(
            self,
            data: QMimeData,
            action: Qt.DropAction,
            row: int = -1,
            col: int = -1,
            parent: QModelIndex = QModelIndex(),
    ):
        if action == Qt.IgnoreAction or not data or not data.hasFormat(
                DEFAULT_MIME_FORMAT):
            return True

        if row < 0 or row > len(self._selected):
            position = len(self._selected)
        else:
            position = self._plugins[row].pluginOrder

        encoded = data.data(DEFAULT_MIME_FORMAT)
        stream = QDataStream(encoded, QIODevice.ReadOnly)

        indexes = []
        while not stream.atEnd():
            srcRow = stream.readInt32()
            stream.readInt32()  # src column
            mapItems = stream.readInt32()  # role data map
            for i in range(mapItems):
                stream.readInt32()  # map role ID
                stream.readQVariant()  # map role value
            indexes.append(self.index(srcRow, 0))

        self.setPluginsOrder(indexes, position)
        return False
Example #15
0
def decode_mime_data(bytearray_):

    data = []
    item = {}

    ds = QDataStream(bytearray_)
    while not ds.atEnd():

        row = ds.readInt32()
        column = ds.readInt32()

        map_items = ds.readInt32()
        for i in range(map_items):
            key = ds.readInt32()

            value = QVariant()
            ds >> value
            item[Qt.ItemDataRole(key)] = value

        data.append(item)

    return data
Example #16
0
 def loadQDataStream(self):
     error = None
     fh = None
     try:
         fh = QFile(self.__fname)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(unicode(fh.errorString()))
         stream = QDataStream(fh)
         magic = stream.readInt32()
         if magic != MovieContainer.MAGIC_NUMBER:
             raise IOError("unrecognized file type")
         version = stream.readInt32()
         if version < MovieContainer.FILE_VERSION:
             raise IOError("old and unreadable file format")
         elif version > MovieContainer.FILE_VERSION:
             raise IOError("new and unreadable file format")
         stream.setVersion(QDataStream.Qt_4_2)
         self.clear(False)
         while not stream.atEnd():
             title = QString()
             acquired = QDate()
             notes = QString()
             stream >> title
             year = stream.readInt16()
             minutes = stream.readInt16()
             stream >> acquired >> notes
             self.add(Movie(title, year, minutes, acquired, notes))
     except (IOError, OSError) as e:
         error = "Failed to load: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Loaded {0} movie records from {1}".format(
             len(self.__movies),
             QFileInfo(self.__fname).fileName())
Example #17
0
    def dropMimeData(self, data: 'QMimeData', action: Qt.DropAction, row: int,
                     column: int, parent: QModelIndex) -> bool:
        if action == Qt.IgnoreAction:
            return True
        if column > 0:
            return False

        if row != -1:
            endRow = row
        elif parent.isValid():
            endRow = parent.row()
        else:
            endRow = self.rowCount(QModelIndex())

        encodedData = data.data('application/x-tableview-dragRow')
        stream = QDataStream(encodedData, QIODevice.ReadOnly)

        beginRows = []
        beginDatas = []
        # newEndRow = endRow
        while not stream.atEnd():
            beginRow = stream.readInt32()
            beginRows.append(beginRow)
            beginDatas.append(self.datas[beginRow])
            if beginRow < endRow - 1:
                endRow = endRow - 1

        beginRows = sorted(beginRows, reverse=True)
        for beginRow in beginRows:
            self.removeRows(beginRow, 1, 0)

        # if endRow == self.rowCount(QModelIndex()) - 1:
        #     endRow = endRow + 1

        for beginData in beginDatas:
            self.beginInsertRows(QModelIndex(), endRow, endRow)
            self.datas.insert(endRow, beginData)
            self.endInsertRows()

            endRow = endRow + 1

        return True
Example #18
0
    def readResponse(self):
        stream = QDataStream(self.socket)
        stream.setVersion(QDataStream.Qt_5_7)

        while True:
            if self.nextBlockSize == 0:
                if self.socket.bytesAvailable() < SIZEOF_UINT16:
                    break
                self.nextBlockSize = stream.readUInt16()
            if self.socket.bytesAvailable() < self.nextBlockSize:
                break
            action = ""
            room = ""
            date = QDate()
            action = stream.readQString()
            room = stream.readQString()
            if action == "BOOKINGSFORROOM":
                dates = []
                for x in range(stream.readInt32()):
                    stream >> date
                    dates.append(str(date.toString(Qt.ISODate)))
                dates = ", ".join(dates)
            if action not in ("BOOKINGSFORROOM", "ERROR"):
                stream >> date
            if action == "ERROR":
                msg = "Error: {0}".format(room)
            elif action == "BOOK":
                msg = "Booked room {0} for {1}".format(
                    room, date.toString(Qt.ISODate))
            elif action == "UNBOOK":
                msg = "Unbooked room {0} for {1}".format(
                    room, date.toString(Qt.ISODate))
            elif action == "BOOKINGSONDATE":
                msg = "Rooms booked on {0}: {1}".format(
                    date.toString(Qt.ISODate), room)
            elif action == "BOOKINGSFORROOM":
                msg = "Room {0} is booked on: {1}".format(room, dates)
            self.responseLabel.setText(msg)
            self.updateUi()
            self.nextBlockSize = 0
Example #19
0
 def open(self):
     self.offerSave()
     path = (QFileInfo(self.filename).path()
             if self.filename else ".")
     fname,filetype = QFileDialog.getOpenFileName(self,
             "Page Designer - Open", path,
             "Page Designer Files (*.pgd)")
     if not fname:
         return
     self.filename = fname
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(str(fh.errorString()))
         items = self.scene.items()
         while items:
             item = items.pop()
             self.scene.removeItem(item)
             del item
         self.addBorders()
         stream = QDataStream(fh)
         stream.setVersion(QDataStream.Qt_5_7)
         magic = stream.readInt32()
         if magic != MagicNumber:
             raise IOError("not a valid .pgd file")
         fileVersion = stream.readInt16()
         if fileVersion != FileVersion:
             raise IOError("unrecognised .pgd file version")
         while not fh.atEnd():
             self.readItemFromStream(stream)
     except IOError as e:
         QMessageBox.warning(self, "Page Designer -- Open Error",
                 "Failed to open {0}: {1}".format(self.filename, e))
     finally:
         if fh is not None:
             fh.close()
     global Dirty
     Dirty = False
Example #20
0
class Reader(QObject):
    def __init__(self, filename):
        self._filename = filename
        self._file = None
        self._dstream = None
        self._version = None

    def __enter__(self):
        self.open()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.close

    def open(self):
        self._file = QFile(self._filename)
        if not self._file.open(QIODevice.ReadOnly):
            raise ValueError("Cannot open " + self._filename)
        self._dstream = QDataStream(self._file)
        self._dstream.setVersion(QDataStream.Qt_4_5)
        for c in b"QGis.MemoryLayerData":

            ct = self._dstream.readUInt8()
            if ct != c:
                raise ValueError(self._filename +
                                 " is not a valid memory layer data file")
        version = self._dstream.readInt32()
        if version not in (1, 2):
            raise ValueError(
                self._filename +
                " is not compatible with this version of the MemoryLayerSaver plugin"
            )
        self._version = version

    def close(self):
        try:
            self._dstream.setDevice(None)
            self._file.close()
        except:  # noqa: E722
            pass
        self._dstream = None
        self._file = None

    def readLayers(self, layers):
        if not self._dstream:
            raise ValueError("Layer stream not open for reading")
        ds = self._dstream

        while True:
            if ds.atEnd():
                return
            id = ds.readQString()
            layer = None
            for l in layers:  # noqa: E741
                if l.id() == id:
                    layer = l
                    break
            if layer is None:
                self.skipLayer()
            else:
                self.readLayer(layer)

    def readLayer(self, layer):
        ds = self._dstream
        dp = layer.dataProvider()
        if dp.featureCount() > 0:
            raise ValueError("Memory layer " + id + " is already loaded")
        attr = dp.attributeIndexes()
        dp.deleteAttributes(attr)
        ss = ""
        if self._version > 1:
            ss = ds.readQString()
        nattr = ds.readInt16()
        attr = list(range(nattr))
        for i in attr:
            name = ds.readQString()
            qtype = ds.readInt16()
            typename = ds.readQString()
            length = ds.readInt16()
            precision = ds.readInt16()
            comment = ds.readQString()
            fld = QgsField(name, qtype, typename, length, precision, comment)
            dp.addAttributes([fld])

        nullgeom = QgsGeometry()
        fields = dp.fields()
        while ds.readBool():
            feat = QgsFeature(fields)
            for i in attr:
                value = ds.readQVariant()
                if value is not None:
                    feat[i] = value

            wkbSize = ds.readUInt32()
            if wkbSize == 0:
                feat.setGeometry(nullgeom)
            else:
                geom = QgsGeometry()
                geom.fromWkb(ds.readRawData(wkbSize))
                feat.setGeometry(geom)
            dp.addFeatures([feat])
        layer.setSubsetString(ss)
        layer.updateFields()
        layer.updateExtents()

    def skipLayer(self):
        ds = self._dstream
        nattr = ds.readInt16()
        attr = list(range(nattr))
        for i in attr:
            name = ds.readQString()  # noqa: F841
            qtype = ds.readInt16()  # noqa: F841
            typename = ds.readQString()  # noqa: F841
            length = ds.readInt16()  # noqa: F841
            precision = ds.readInt16()  # noqa: F841
            comment = ds.readQString()  # noqa: F841
        while ds.readBool():
            for i in attr:
                ds.readQVariant()
            wkbSize = ds.readUInt32()
            if wkbSize > 0:
                ds.readRawData(wkbSize)
Example #21
0
class QmyMainWindow(QMainWindow): 
   def __init__(self, parent=None):
      super().__init__(parent)    #调用父类构造函数,创建窗体
      self.ui=Ui_MainWindow()     #创建UI对象
      self.ui.setupUi(self)       #构造UI界面

      self.ui.groupBox.setEnabled(False)
      self.ui.actSaveALL.setEnabled(False)
      self.ui.actReadALL.setEnabled(False)

      self.setWindowTitle("二进制文件流化读写")
      
      self.__testFileName=""   #测试用文件的文件名
      
##  ==============自定义功能函数============
   def __iniWrite(self):     ##初始化写文件操作
      self.fileDevice=QFile(self.__testFileName)    #创建文件对象
      if  not self.fileDevice.open(QIODevice.WriteOnly):
         del self.fileDevice    #删除对象
         return False

      self.fileStream=QDataStream(self.fileDevice)   #流对象

      self.fileStream.setVersion(QDataStream.Qt_5_12)   #设置版本号,写入和读取的版本号要兼容
      if self.ui.radio_BigEndian.isChecked():
         self.fileStream.setByteOrder(QDataStream.BigEndian)
      else:
         self.fileStream.setByteOrder(QDataStream.LittleEndian)

      ##必须要设置精度,float和double都按照这个精度
      precision=QDataStream.DoublePrecision
      if self.ui.radio_Single.isChecked(): 
         precision=QDataStream.SinglePrecision
      self.fileStream.setFloatingPointPrecision(precision)
      return True

   def __delFileStream(self): ##结束写文件操作
      self.fileDevice.close()
      del self.fileStream
      del self.fileDevice


   def __iniRead(self):  ##开始读文件操作
      if not QFile.exists(self.__testFileName):
         QMessageBox.critical(self,"错误","文件不存在")
         return False
      
      self.fileDevice=QFile(self.__testFileName)    #创建文件对象
      if  not self.fileDevice.open(QIODevice.ReadOnly):
         del self.fileDevice    #删除对象
         return False

      self.fileStream=QDataStream(self.fileDevice)
      self.fileStream.setVersion(QDataStream.Qt_5_12)   #设置流版本号,写入和读取的版本号要兼容

      if self.ui.radio_BigEndian.isChecked():
         self.fileStream.setByteOrder(QDataStream.BigEndian)
      else:
         self.fileStream.setByteOrder(QDataStream.LittleEndian)

      ##必须要设置精度,float和double都按照这个精度
      precision=QDataStream.DoublePrecision
      if self.ui.radio_Single.isChecked(): 
         precision=QDataStream.SinglePrecision
      self.fileStream.setFloatingPointPrecision(precision)

      return True
          
##  ==========由connectSlotsByName() 自动连接的槽函数==================
   
   @pyqtSlot()    ##选择测试用文件
   def on_btnFile_clicked(self):  
      curPath=QDir.currentPath()       #当前目录
      title="选择文件"                 #对话框标题
      filt="流数据文件(*.stream)"     #文件过滤器
      fileName,flt=QFileDialog.getSaveFileName(self,title,curPath,filt)
      if (fileName == ""):
         return

      self.__testFileName=fileName     #测试用文件
      self.ui.editFilename.setText(fileName)
      self.ui.groupBox.setEnabled(True)
      self.ui.actSaveALL.setEnabled(True)
      self.ui.actReadALL.setEnabled(True)


   @pyqtSlot()   ##写  int8
   def on_btnInt8_Write_clicked(self):  
      Value=self.ui.spin_Int8.value() #Python int
      if self.__iniWrite():
         try:
            self.fileStream.writeInt8(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeInt8()出现错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  int8
   def on_btnInt8_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readInt8()
         self.ui.edit_Int8.setText("%d"%Value)
         self.__delFileStream()

   @pyqtSlot()   ##写  uint8
   def on_btnUInt8_Write_clicked(self):  
      Value=self.ui.spin_UInt8.value()
      if self.__iniWrite(): 
         try:
            self.fileStream.writeUInt8(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeUInt8()出现错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  uint8
   def on_btnUInt8_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readUInt8()
         self.ui.edit_UInt8.setText("%d"%Value)
         self.__delFileStream()


   @pyqtSlot()    ##写int16
   def on_btnInt16_Write_clicked(self):  
      Value=self.ui.spin_Int16.value()       #Python的int
      if self.__iniWrite():
         try:
            self.fileStream.writeInt16(Value)   #以int16类型写入文件
         except Exception as e:
            QMessageBox.critical(self, "writeInt16()发生错误", str(e))
         finally:
            self.__delFileStream()
##            print("finally被执行")
          
   @pyqtSlot()    ##读 int16
   def on_btnInt16_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readInt16() 
            self.ui.edit_Int16.setText("%d"%Value)
         except Exception as e:
            QMessageBox.critical(self, "readInt16()发生错误", str(e))
         finally:
            self.__delFileStream()
##            print("finally被执行")
            
            
   @pyqtSlot()   ##写  uint16
   def on_btnUInt16_Write_clicked(self):  
      Value=self.ui.spin_UInt16.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeUInt16(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeUInt16()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  uint16
   def on_btnUIn16_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readUInt16()
         self.ui.edit_UInt16.setText("%d"%Value)
         self.__delFileStream()

         
   @pyqtSlot()   ##写  int32
   def on_btnInt32_Write_clicked(self):  
      Value=self.ui.spin_Int32.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeInt32(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeInt32()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  int32
   def on_btnInt32_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readInt32()
         self.ui.edit_Int32.setText("%d"%Value)
         self.__delFileStream()


   @pyqtSlot()   ##写  int64
   def on_btnInt64_Write_clicked(self):  
      Value=self.ui.spin_Int64.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeInt64(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeInt64()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  int64
   def on_btnInt64_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readInt64()
         self.ui.edit_Int64.setText("%d"%Value)
         self.__delFileStream()


   @pyqtSlot()   ##写  int
   def on_btnInt_Write_clicked(self):  
      Value=self.ui.spin_Int.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeInt(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeInt()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  int
   def on_btnInt_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readInt()
         self.ui.edit_Int.setText("%d"%Value)
         self.__delFileStream()


   @pyqtSlot()   ##写  bool
   def on_btnBool_Write_clicked(self):  
      Value=self.ui.chkBox_In.isChecked() #bool型
      if self.__iniWrite(): 
         self.fileStream.writeBool(Value)
         self.__delFileStream()
          
   @pyqtSlot()    ##读  bool
   def on_btnBool_Read_clicked(self):  
      if self.__iniRead():
         Value=self.fileStream.readBool() #bool型
         self.ui.chkBox_Out.setChecked(Value)
         self.__delFileStream()


   @pyqtSlot()   ##写  float
   def on_btnFloat_Write_clicked(self):  
      Value=self.ui.spin_Float.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeFloat(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeFloat()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  float
   def on_btnFloat_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readFloat()
            self.ui.edit_Float.setText("%.4f"%Value)
         except Exception as e:
            QMessageBox.critical(self, "writeFloat()发生错误", str(e))
         finally:
            self.__delFileStream()


   @pyqtSlot()   ##写  double
   def on_btnDouble_Write_clicked(self):  
      Value=self.ui.spin_Double.value()
      if self.__iniWrite():
         try:
            self.fileStream.writeDouble(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeDouble()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读  double
   def on_btnDouble_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readDouble()
            self.ui.edit_Double.setText("%.4f"%Value)
         except Exception as e:
            QMessageBox.critical(self, "readDouble()发生错误", str(e))
         finally:
            self.__delFileStream()


   @pyqtSlot()    ##写 QString,与Python的str兼容
   def on_btnQStr_Write_clicked(self):  
      Value=self.ui.editQStr_In.text()
      if self.__iniWrite():
         try:
            self.fileStream.writeQString(Value)
         except Exception as e:
            QMessageBox.critical(self, "writeQString()发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读 QString,与Python的str兼容
   def on_btnQStr_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readQString()
            self.ui.editQStr_Out.setText(Value)
         except Exception as e:
            QMessageBox.critical(self, "readQString()发生错误", str(e))
         finally:
            self.__delFileStream()

   @pyqtSlot()    ##写 String
   def on_btnStr_Write_clicked(self):  
      strV=self.ui.editStr_In.text()   #str类型
      if self.__iniWrite():
         try:
            bts=bytes(strV,encoding="utf-8")  #转换为bytes类型
            self.fileStream.writeString(bts)
         except Exception as e:
            QMessageBox.critical(self, "写入时发生错误", str(e))
         finally:
            self.__delFileStream()
          
   @pyqtSlot()    ##读 String
   def on_btnStr_Read_clicked(self):  
      if self.__iniRead():
         try:
            Value=self.fileStream.readString()  #bytes类型
            strV=Value.decode("utf-8")          #从bytes类型解码为字符串,编码utf-8
            self.ui.editStr_Out.setText(strV)
         except Exception as e:
            QMessageBox.critical(self, "读取时发生错误", str(e))
         finally:
            self.__delFileStream()

##===字体的写入与读取
   @pyqtSlot()   ##选择字体
   def on_btnFont_In_clicked(self):  
      font=self.ui.btnFont_In.font()
      font,OK=QFontDialog.getFont(font,self) #选择字体
      if OK:
         self.ui.btnFont_In.setFont(font)

   @pyqtSlot()   ##写  QVariant, QFont
   def on_btnFont_Write_clicked(self):  
      font=self.ui.btnFont_In.font()    #QFont类型
      if self.__iniWrite(): 
         self.fileStream.writeQVariant(font)  #QFont类型
         self.__delFileStream()
          
   @pyqtSlot()    ##读  QVariant, QFont
   def on_btnFont_Read_clicked(self):  
      if self.__iniRead():
         try:
            font=self.fileStream.readQVariant()   #QFont类型
            self.ui.editFont_Out.setFont(font)
         except Exception as e:
            QMessageBox.critical(self, "读取时发生错误", str(e))
         finally:
            self.__delFileStream()


##===颜色的写入与读取
   @pyqtSlot()   ##选择颜色
   def on_btnColor_In_clicked(self):  
      plet=self.ui.btnColor_In.palette()  #QPalette
      color=plet.buttonText().color()     #QColor
      color= QColorDialog.getColor(color,self)
      if color.isValid():
         plet.setColor(QPalette.ButtonText,color)
         self.ui.btnColor_In.setPalette(plet)


   @pyqtSlot()   ##写  QVariant, QColor
   def on_btnColor_Write_clicked(self):  
      plet=self.ui.btnColor_In.palette()  
      color=plet.buttonText().color()     #QColor
      if self.__iniWrite(): 
         self.fileStream.writeQVariant(color)  #QColor
         self.__delFileStream()
          
   @pyqtSlot()    ##读  QVariant, QColor
   def on_btnColor_Read_clicked(self):  
      if self.__iniRead():
         try:
            color=self.fileStream.readQVariant()   #读取为QColor类型
            plet=self.ui.editColor_Out.palette() 
            plet.setColor(QPalette.Text,color)
            self.ui.editColor_Out.setPalette(plet)
         except Exception as e:
            QMessageBox.critical(self, "读取时发生错误", str(e))
         finally:
            self.__delFileStream()

   @pyqtSlot()    ##读出编辑框全清空
   def on_actClearOutput_triggered(self):  
      self.ui.edit_Int8.clear()
      self.ui.edit_UInt8.clear()
      self.ui.edit_Int16.clear()
      self.ui.edit_UInt16.clear()
      self.ui.edit_Int32.clear()
      self.ui.edit_Int64.clear()
      self.ui.edit_Int.clear()

      self.ui.edit_Float.clear()
      self.ui.edit_Double.clear()

      font=self.font()
      self.ui.editFont_Out.setFont(font)

      plet=self.palette()
      self.ui.editColor_Out.setPalette(plet)

   @pyqtSlot()    ##连续写入文件
   def on_actSaveALL_triggered(self):  
      if not self.__iniWrite():
         QMessageBox.critical(self,"错误","为写入打开文件时出错")
         return
   #数据写入部分
      Value=self.ui.spin_Int8.value()
      self.fileStream.writeInt8(Value)    #int8

      Value=self.ui.spin_UInt8.value()
      self.fileStream.writeUInt8(Value)   #uint8

      Value=self.ui.spin_Int16.value()
      self.fileStream.writeInt16(Value)   #int16

      Value=self.ui.spin_UInt16.value()
      self.fileStream.writeUInt16(Value)  #uint16

      Value=self.ui.spin_Int32.value()
      self.fileStream.writeInt32(Value)   #int32

      Value=self.ui.spin_Int64.value()
      self.fileStream.writeInt64(Value)   #int64

      Value=self.ui.spin_Int.value()
      self.fileStream.writeInt(Value)     #int

      Value=self.ui.chkBox_In.isChecked()
      self.fileStream.writeBool(Value)    #bool

      Value=self.ui.spin_Float.value()
      self.fileStream.writeFloat(Value)   #float

      Value=self.ui.spin_Double.value() 
      self.fileStream.writeDouble(Value)  #double

      str_Value=self.ui.editQStr_In.text()
      self.fileStream.writeQString(str_Value)   #QString
      
      str_Value=self.ui.editStr_In.text()       #str类型
      bts=bytes(str_Value,encoding="utf-8")     #转换为bytes类型
      self.fileStream.writeString(bts)    

      font=self.ui.btnFont_In.font()
      self.fileStream.writeQVariant(font)    #QFont

      plet=self.ui.btnColor_In.palette()
      color=plet.buttonText().color() 
      self.fileStream.writeQVariant(color)   #QColor

   #数据写入完成
      self.__delFileStream()
      QMessageBox.information(self,"消息","数据连续写入完成.")


   @pyqtSlot()    ##连续读取文件
   def on_actReadALL_triggered(self):  
      if not self.__iniRead():
         QMessageBox.critical(self,"错误","为读取打开文件时出错")
         return
      
   #数据读取部分
      Value=self.fileStream.readInt8()    #int8
      self.ui.edit_Int8.setText("%d"%Value)

      Value=self.fileStream.readUInt8()   #uint8
      self.ui.edit_UInt8.setText("%d"%Value)

      Value=self.fileStream.readInt16()   #int16
      self.ui.edit_Int16.setText("%d"%Value)

      Value=self.fileStream.readUInt16()  #uint16
      self.ui.edit_UInt16.setText("%d"%Value)

      Value=self.fileStream.readInt32()   #int32
      self.ui.edit_Int32.setText("%d"%Value)

      Value=self.fileStream.readInt64()   #int64
      self.ui.edit_Int64.setText("%d"%Value)

      Value=self.fileStream.readInt()     #int
      self.ui.edit_Int.setText("%d"%Value)

      Value=self.fileStream.readBool()    #bool
      self.ui.chkBox_Out.setChecked(Value)

      Value=self.fileStream.readFloat()   #float
      self.ui.edit_Float.setText("%.4f"%Value)

      Value=self.fileStream.readDouble()  #double
      self.ui.edit_Double.setText("%.4f"%Value)

      str_Value=self.fileStream.readQString()  #str
      self.ui.editQStr_Out.setText(str_Value)

      byteStr=self.fileStream.readString()   #bytes
      str_Value=byteStr.decode("utf-8")      #从bytes类型解码为字符串
      self.ui.editStr_Out.setText(str_Value)

      font=self.fileStream.readQVariant()    #QFont
      self.ui.editFont_Out.setFont(font)

      color=self.fileStream.readQVariant()   #QColor
      plet=self.ui.editColor_Out.palette() 
      plet.setColor(QPalette.Text,color)
      self.ui.editColor_Out.setPalette(plet)
      
   #数据写入完成
      self.__delFileStream()
      QMessageBox.information(self,"消息","数据连续读取完成.")