def smethod_0(iwin32Window_0): RunwayList.RunwayList() runwayList = RunwayList() if (not QFile.exists(RunwayList.fileName)): return runwayList # try # { file0 = QFile(RunwayList.fileName) file0.open(QIODevice.ReadOnly) dataStream = QDataStream(file0) # using (BinaryReader binaryReader = new BinaryReader(File.Open(RunwayList.fileName, FileMode.Open, FileAccess.Read))) # { str0 = dataStream.readQString( ) #Encoding.Default.GetString(binaryReader.ReadBytes("PHXASA".Length)) num = dataStream.readInt() #binaryReader.ReadByte() if (not str0 == "PHXASA" or (num != 2 and num != 3)): return runwayList num1 = dataStream.readInt() for i in range(num1): runwayList.Add(Runway.smethod_0(dataStream, num)) # catch (Exception exception1) # { # Exception exception = exception1 # ErrorMessageBox.smethod_0(iwin32Window_0, string.Format(Messages.ERR_FAILED_TO_LOAD_RWY_DATA_FILE, exception.Message)) # } runwayList.method_1() return runwayList
def save(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError("no filename specified for saving") fh = QFile(self.filename) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) stream.writeInt32(MAGIC_NUMBER) stream.writeInt16(FILE_VERSION) stream.setVersion(QDataStream.Qt_4_1) for ship in self.ships: stream << ship.name << ship.owner << ship.country \ << ship.description stream.writeInt32(ship.teu) self.dirty = False except IOError as e: exception = e finally: if fh is not None: fh.close() if exception is not None: raise exception
def load(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError, "no filename specified for loading" fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(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 = QString() owner = QString() country = QString() description = QString() stream >> name >> owner >> country >> description teu = stream.readInt32() self.ships.append(Ship(name, owner, country, teu, description)) self.owners.add(unicode(owner)) self.countries.add(unicode(country)) self.dirty = False except IOError, e: exception = e
def open(self): self.offerSave() path = (QFileInfo(self.filename).path() if not self.filename.isEmpty() else ".") fname = QFileDialog.getOpenFileName(self, "Page Designer - Open", path, "Page Designer Files (*.pgd)") if fname.isEmpty(): return self.filename = fname fh = None try: fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(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_4_2) 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, e: QMessageBox.warning(self, "Page Designer -- Open Error", "Failed to open {0}: {1}".format(self.filename, e))
def test_dropping_the_data_emits_the_signal(self): mw = self._get_one() self.assertEqual(mw.supportedDropActions(), Qt.CopyAction) self.assertIn('application/vnd.re-eat.recipe', mw.mimeTypes()) assert mw.viewport().acceptDrops() mw.recipeAdded = DummySignal() mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) stream.writeInt(1) stream.writeInt(2) mimeData.setData('application/vnd.re-eat.recipe', encodedData) mw.dropMimeData(0, mimeData, Qt.CopyAction) self.assertListEqual(mw.recipeAdded.received, [(1, mw.date, mw.index), (2, mw.date, mw.index)]) mw.recipeMoved = DummySignal() mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) stream.writeInt(42) stream.writeQVariant(datetime.date.today()) stream.writeInt(2) mimeData.setData('application/vnd.re-eat.meal_recipe', encodedData) mw.dropMimeData(0, mimeData, Qt.CopyAction) self.assertListEqual(mw.recipeMoved.received, [(42, datetime.date.today(), 2, mw.date, mw.index)])
def saveQDataStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) stream.writeInt32(MovieContainer.MAGIC_NUMBER) stream.writeInt32(MovieContainer.FILE_VERSION) stream.setVersion(QDataStream.Qt_4_2) for key, movie in self.__movies: stream << movie.title stream.writeInt16(movie.year) stream.writeInt16(movie.minutes) stream << movie.acquired << movie.location \ << movie.notes except EnvironmentError as e: error = "Failed to save: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Saved {0} movie records to {1}".format( len(self.__movies), QFileInfo(self.__fname).fileName())
def open_to_stream(filename, mode, stream_version=QDataStream.Qt_4_5): file = QFile(filename) file.open(mode) stream = QDataStream(file) stream.setVersion(stream_version) return FileStream(file, stream)
def read_project(settings, openFileName): """ Toplevel reader routine. """ status = None handle = None try: handle = QFile(openFileName) if not handle.open(QIODevice.ReadOnly): raise IOError(handle.errorString()) stream = QDataStream(handle) # check header magic = stream.readInt32() if magic != MAGIC_NUMBER: status = ("Unrecognized file type - \n{0}\nis not " "a sconcho spf file!").format(openFileName) raise IOError(status) version = stream.readInt32() stream.setVersion(QDataStream.Qt_4_5) # initialize API specific entries repeatLegends = {} rowRepeats = [] textItems = [] rowLabels = {} columnLabels = {} if version == 1: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats) = read_API_1_version(stream, settings) elif version == 2: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems) = \ read_API_2_version(stream, settings) elif version == 3: (patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels) = \ read_API_3_version(stream, settings) else: raise IOError("unsupported API version") except (IOError, OSError) as e: status = "Failed to open %s: %s " % (openFileName, e) finally: if handle is not None: handle.close() if status is not None: return (False, status, None, None, None, None, None, None, None, None) return (True, None, patternGridItems, legendItems, colors, activeSymbol, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels)
def readResponse(self): global paralen global words stream = QDataStream(self.socket) stream.setVersion(QDataStream.Qt_4_2) while True: if self.nextBlockSize == 0: if self.socket.bytesAvailable() < SIZEOF_UINT16: break self.nextBlockSize = stream.readUInt16() if self.socket.bytesAvailable() < self.nextBlockSize: break inpdata = QString() stream >> inpdata s = str(inpdata) s = s.split(" ", 1) global flag2 if flag2 == 1: if int(s[0]) == 1000 and (s[1]) == "0": self.lbl.setText( "<font size='8'>Waiting for other players . . . </font>" ) else: flag2 = 0 # flag2==0: para is fetched and game is not finished parastr = s[1].split(" ", 1) n = int(str(parastr[0])) allparas = paralist() global paragraph global paralen paragraph = parastr[1] paralen = len(paragraph.split()) self.lbl.setText("<font size=\"" + str(paratextsize) + "\">" + paragraph + "</font>") self.lcdwpm.display(0) self.lcdaccuracy.display(0) self.lcdtimer.display(0) self.progbar.setValue(0) self.exitlbl.setVisible(False) updatecurrentWordFromPara() global totalChars totalChars = len(paragraph) self.timer.stop() self.qle.setReadOnly(True) self.timer2.start(1000) if flag2 == 2: if int(s[0]) == 1009: self.lbl.setText(s[1]) self.lbl.setStyleSheet( _fromUtf8("font: 24pt \"mry_KacstQurn\";" "color:#4C3327;")) elif flag2 == 0 and int(s[0]) != 1000 and int( s[0]) != 1010 and int(s[0]) != 1009: self.lcdaccuracy.display(int(str(inpdata))) self.nextBlockSize = 0
def mimeData(self, items): mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) for item in items: id = item.data(Qt.UserRole) stream.writeInt(id) mimeData.setData('application/vnd.re-eat.recipe', encodedData) return mimeData
def saveQDataStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) stream.writeInt32(MovieContainer.MAGIC_NUMBER) stream.writeInt32(MovieContainer.FILE_VERSION) stream.setVersion(QDataStream.Qt_4_2) for key, movie in self.__movies: stream << movie.title stream.writeInt16(movie.year) stream.writeInt16(movie.minutes) stream << movie.acquired << movie.notes except EnvironmentError as e: error = "Failed to save: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Saved {0} movie records to {1}".format( len(self.__movies), QFileInfo(self.__fname).fileName())
def issueRequest(self, inpdata): self.request = QByteArray() stream = QDataStream(self.request, QIODevice.WriteOnly) stream.setVersion(QDataStream.Qt_4_2) stream.writeUInt16(0) stream << inpdata stream.device().seek(0) stream.writeUInt16(self.request.size() - SIZEOF_UINT16) if self.socket.isOpen(): self.socket.close() self.socket.connectToHost("127.0.0.1", PORT)
def test_drag_information_are_correct(self): rw = RecipesWidget() self.assertIn('application/vnd.re-eat.recipe', rw.mimeTypes()) items = [rw.item(i) for i in (0, 1)] ids = [item.data(Qt.UserRole) for item in items] data = rw.mimeData(items) stream = QDataStream(data.data('application/vnd.re-eat.recipe')) result = [] while not stream.atEnd(): result.append(stream.readInt()) self.assertListEqual(result, ids)
def test_mime_data(self): class DummyItem(object): def data(s, role): self.assertEqual(role, Qt.UserRole) return 42 mw = self._get_one() data = mw.mimeData([DummyItem()]).data('application/vnd.re-eat.meal_recipe') stream = QDataStream(data, QIODevice.ReadOnly) self.assertEqual(stream.readInt(), 42) self.assertEqual(stream.readQVariant(), mw.date) self.assertEqual(stream.readInt(), mw.index)
def test_mime_data(self): class DummyItem(object): def data(s, role): self.assertEqual(role, Qt.UserRole) return 42 mw = self._get_one() data = mw.mimeData([DummyItem() ]).data('application/vnd.re-eat.meal_recipe') stream = QDataStream(data, QIODevice.ReadOnly) self.assertEqual(stream.readInt(), 42) self.assertEqual(stream.readQVariant(), mw.date) self.assertEqual(stream.readInt(), mw.index)
def changeResolution(self): fileName = QFileDialog.getOpenFileName( self, 'Load .prn file', directory=self.settings.value('unpacker/dir_open', QDir.currentPath()), filter='PRN files (*.prn *.bin);;All (*)') if not fileName: return file = QFile(fileName) if not file.open(QFile.ReadWrite): QMessageBox.warning( self, "Unpacker .prn", "Unable load file {}:\n{}.".format(fileName, file.errorString())) return self.settings.setValue('unpacker/dir_open', QFileInfo(file).path()) data = QDataStream(file) data.setByteOrder(QDataStream.LittleEndian) headerVersion = data.readInt32() xdpi = data.readInt32() ydpi = data.readInt32() dialog = ChangeResolutionDialog(xdpi, ydpi, self) if dialog.exec_(): file.seek(4) data.writeInt32(dialog.sbXdpi.value()) data.writeInt32(dialog.sbYdpi.value()) self.status.showMessage("Resolution changed successful", 7000) file.close()
def method_0(self, iwin32Window_0): if QFile.exists(RunwayList.fileName): fl = QFile.remove(RunwayList.fileName) file0 = QFile(RunwayList.fileName) file0.open(QIODevice.WriteOnly) # f = open(RunwayList.fileName, 'w') # file0.flush() # file0.close() else: file0 = QFile(RunwayList.fileName) file0.open(QIODevice.WriteOnly) # f = open(RunwayList.fileName, 'w') # file0.flush() # file0.close() # file0 = QFile(RunwayList.fileName) # file0.open(QIODevice.WriteOnly) dataStream = QDataStream(file0) dataStream.writeQString(QString("PHXASA")) dataStream.writeInt(3) dataStream.writeInt(len(self)) for runway in self: runway.method_8(dataStream)
def dropMimeData(self, index, data, action): if action == Qt.IgnoreAction: return True if data.hasFormat('application/vnd.re-eat.meal_recipe'): encodedData = data.data('application/vnd.re-eat.meal_recipe') stream = QDataStream(encodedData, QIODevice.ReadOnly) while not stream.atEnd(): id = stream.readInt() date = stream.readQVariant() index = stream.readInt() self.recipeRemoved.emit(id, date, index) return True return False
def mimeData(self, indexes): mime_data = QMimeData() encoded_data = QByteArray() stream = QDataStream(encoded_data, QIODevice.WriteOnly) ref = self.get_current_branch() or self.get_remote_ref() for index in indexes: if index.isValid() and index.column() == 0: text = QString(ref.name + " ") text += QString(str(index.row())) stream.writeQString(text) mime_data.setData("application/vnd.text.list", encoded_data) return mime_data
def mimeData(self, indexes): mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) for index in indexes: if not index.isValid(): continue if not isinstance(index.internalPointer(), TableItem): continue table = self.getItem(index) stream.writeQString(table.mimeUri()) mimeData.setData(self.QGIS_URI_MIME, encodedData) return mimeData
def _loadRulesByExport(self, e_file): qfile = QFile(e_file) if qfile.open(QIODevice.ReadOnly): inp = QDataStream(qfile) inp.setVersion(QDataStream.Qt_4_5) tmp = inp.readQVariantHash() #tmp = QVariant(inp) rules = self._loadRulesFromVariantHash(tmp) qfile.close() #if (tmp.isEmpty()) #return false; #qDebug("Processing was successful!"); return rules else: print "error: file " + file + "not open" return None
def run(self): fh = QFile(self.filename) fhlen = self._file_len(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) self.data_block = {} stream = QDataStream(fh) stream.setVersion(QDataStream.Qt_4_2) magic = stream.readInt32() if magic != gMAGICNUM: raise IOError, "not a valid .jd file" fileVersion = stream.readInt16() if fileVersion != gFILEVERSION: raise IOError, "unrecognised .jd file version" while not fh.atEnd(): self._ReadItemFromStream(stream) self.emit(SIGNAL("PROJECTLOADERDONE(PyQt_PyObject)"), self.data_block)
def save_project(canvas, colors, activeSymbol, settings, saveFileName): """ Toplevel writer routine. """ # prepare data structures patternGridItems = get_patternGridItems(canvas) legendItems = canvas.gridLegend.values() patternRepeats = get_patternRepeats(canvas) repeatLegends = canvas.repeatLegend rowRepeats = canvas.rowRepeatTracker rowLabels = canvas.rowLabels columnLabels = canvas.columnLabels textItems = canvas.canvasTextBoxes assert (len(patternRepeats) == len(repeatLegends)) status = None handle = None try: handle = QFile(saveFileName) if not handle.open(QIODevice.WriteOnly | QIODevice.Truncate): raise IOError(unicode(handle.errorString())) stream = QDataStream(handle) # write header stream.writeInt32(MAGIC_NUMBER) stream.writeInt32(API_VERSION) stream.setVersion(QDataStream.Qt_4_5) # write content write_patternGridItems(stream, patternGridItems) write_legendItems(stream, legendItems) write_colors(stream, colors) write_active_symbol(stream, activeSymbol) write_patternRepeats(stream, patternRepeats) write_repeatLegends(stream, repeatLegends) write_rowRepeats(stream, rowRepeats) write_textItems(stream, textItems) write_row_labels(stream, rowLabels) write_column_labels(stream, columnLabels) write_settings(stream, settings) except (IOError, OSError) as e: status = "Failed to save: %s " % e finally: if handle is not None: handle.close() if status is not None: return (False, status) return (True, None)
def smethod_0(iwin32Window_0): FatoList.FatoList() fatoList = FatoList() if (not QFile.exists(FatoList.fileName)): return fatoList file0 = QFile(FatoList.fileName) file0.open(QIODevice.ReadOnly) dataStream = QDataStream(file0) str0 = dataStream.readQString() num = dataStream.readInt() if (not (str0 == "PHXHSAF") or num != 1): raise Messages.ERR_INVALID_FILE_FORMAT # throw new Exception(Messages.ERR_INVALID_FILE_FORMAT) num1 = dataStream.readInt() for i in range(num1): fatoList.append(Fato.smethod_0(dataStream, num)) fatoList.method_1() return fatoList
def saveState(self): """ Return the toolbox state (as a `QByteArray`). .. note:: Individual tabs are stored by their action's text. """ version = 2 actions = map(self.tabAction, range(self.count())) expanded = [action for action in actions if action.isChecked()] expanded = [action.text() for action in expanded] byte_array = QByteArray() stream = QDataStream(byte_array, QIODevice.WriteOnly) stream.writeInt(version) stream.writeQStringList(expanded) return byte_array
def save(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError, "no filename specified for saving" fh = QFile(self.filename) if not fh.open(QIODevice.WriteOnly): raise IOError, unicode(fh.errorString()) stream = QDataStream(fh) stream.writeInt32(MAGIC_NUMBER) stream.writeInt16(FILE_VERSION) stream.setVersion(QDataStream.Qt_4_1) for ship in self.ships.values(): stream << ship.name << ship.owner << ship.country stream << ship.description stream.writeInt32(ship.teu) self.dirty = False except IOError, err: exception = err
def loadQDataStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) magic = stream.readInt32() if magic != MovieContainer.MAGIC_NUMBER: raise IOError("unrecognized file type") version = stream.readInt32() if version < MovieContainer.OLD_FILE_VERSION: raise IOError("old and unreadable file format") elif version > MovieContainer.FILE_VERSION: raise IOError("new and unreadable file format") old = False if version == MovieContainer.OLD_FILE_VERSION: old = True stream.setVersion(QDataStream.Qt_4_2) self.clear(False) while not stream.atEnd(): title = QString() acquired = QDate() location = QString() notes = QString() stream >> title year = stream.readInt16() minutes = stream.readInt16() if old: stream >> acquired >> notes else: stream >> acquired >> location >> notes self.add(Movie(title, year, minutes, acquired, location, notes)) except EnvironmentError 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())
def restoreState(self, state): """ Restore the toolbox from a :class:`QByteArray` `state`. .. note:: The toolbox should already be populated for the state changes to take effect. """ # In version 1 of saved state the state was saved in # a simple dict repr string. if isinstance(state, QByteArray): stream = QDataStream(state, QIODevice.ReadOnly) version = stream.readInt() if version == 2: expanded = stream.readQStringList() for action in map(self.tabAction, range(self.count())): if (action.text() in expanded) != action.isChecked(): action.trigger() return True return False
def startDrag(self, drop_actions): selected_doc_items = self.selectedItems() data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) for doc_item in selected_doc_items: stream.writeQString(doc_item.text() + ":" + doc_item.get_full_name()) mimeData = QMimeData() mimeData.setData("application/x-doc-list", data) drag = QDrag(self) drag.setMimeData(mimeData) drag.setHotSpot(QPoint(0, 0)) if drag.start(Qt.MoveAction) == Qt.MoveAction: docs = [] for doc_item in selected_doc_items: # self.takeItem(self.row(doc_item)) docs.append(doc_item.text()) self.emit(SIGNAL("removeDocs"), docs)
def _parse(self): if self.buffer.bytesAvailable() >= 4: stream = QDataStream(self.buffer) msg = Message.fromInt(stream.readInt32()) if msg == None: return args = [] bytesRead = 4 for aType in msg.argTypes: if aType == str: if self.buffer.bytesAvailable() < 4: return length = stream.readInt32() if self.buffer.bytesAvailable() < length: return args.append(stream.readRawData(length)) bytesRead += 4 + length elif aType == int: if self.buffer.bytesAvailable() < 4: return args.append(stream.readInt32()) bytesRead += 4 elif aType == long: if self.buffer.bytesAvailable() < 8: return args.append(stream.readInt64()) bytesRead += 8 return (msg, args, bytesRead)
def load(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError, "no filename specified for loading" fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(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 = QString() owner = QString() country = QString() description = QString() stream >> name >> owner >> country >> description teu = stream.readInt32() self.ships.append(Ship(name, owner, country, teu, description)) self.owners.add(unicode(owner)) self.countries.add(unicode(country)) self.dirty = False except IOError, err: exception = err
def dropMimeData(self, data, action, row, column, parent): # 如果放入动作是Qt.IgnoreAction,那么返回True if (action == Qt.IgnoreAction): return True # 如果数据的格式不是指定的格式,那么返回False if (not data.hasFormat("application/vnd.text.list")): return False # 因为这里是列表,只用一列,所以列大于0时返回False if (column > 0): return False # 设置开始插入的行 if (row != -1): beginRow = row elif parent.isValid(): beginRow = parent.row() else: beginRow = self.rowCount(QModelIndex()) # 将数据从QMimeData中读取出来,然后插入到模型中 encodedData = data.data("application/vnd.text.list") stream = QDataStream(encodedData, QIODevice.ReadOnly) newItems = QStringList() rows = 0 while (not stream.atEnd()): text = QString() stream >> text newItems.append(text) rows += 1 self.insertRows(beginRow, rows, QModelIndex()) for text in newItems: idx = self.index(beginRow, 0, QModelIndex()) self.setData(idx, QVariant(text)) beginRow += 1 return True
def save_project(canvas, colors, activeSymbol, settings, saveFileName): """ Toplevel writer routine. """ # prepare data structures patternGridItems = get_patternGridItems(canvas) legendItems = canvas.gridLegend.values() patternRepeats = get_patternRepeats(canvas) repeatLegends = canvas.repeatLegend rowRepeats = canvas.rowRepeatTracker rowLabels = canvas.rowLabels columnLabels = canvas.columnLabels textItems = canvas.canvasTextBoxes assert(len(patternRepeats) == len(repeatLegends)) status = None handle = None try: handle = QFile(saveFileName) if not handle.open(QIODevice.WriteOnly | QIODevice.Truncate): raise IOError(unicode(handle.errorString())) stream = QDataStream(handle) # write header stream.writeInt32(MAGIC_NUMBER) stream.writeInt32(API_VERSION) stream.setVersion(QDataStream.Qt_4_5) # write content write_patternGridItems(stream, patternGridItems) write_legendItems(stream, legendItems) write_colors(stream, colors) write_active_symbol(stream, activeSymbol) write_patternRepeats(stream, patternRepeats) write_repeatLegends(stream, repeatLegends) write_rowRepeats(stream, rowRepeats) write_textItems(stream, textItems) write_row_labels(stream, rowLabels) write_column_labels(stream, columnLabels) write_settings(stream, settings) except (IOError, OSError) as e: status = "Failed to save: %s " % e finally: if handle is not None: handle.close() if status is not None: return (False, status) return (True, None)
def run(self): tcpSocket = QTcpSocket() if not tcpSocket.setSocketDescriptor(self.socketDescriptor): self.error.emit(tcpSocket.error()) return self._stream = QDataStream(tcpSocket) print('text stream created') while not self.shoudDisconnect: print(tcpSocket.bytesAvailable()) while tcpSocket.bytesAvailable(): pass
def mimeData(self, indexes): _mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) for index in indexes: if (index.isValid()): text = self.data(index, Qt.DisplayRole).toString() stream << text # 将数据放入QMimeData中 _mimeData.setData("application/vnd.text.list", encodedData) return _mimeData
def dropMimeData(self, index, data, action): if action == Qt.IgnoreAction: return True if data.hasFormat('application/vnd.re-eat.recipe'): encodedData = data.data('application/vnd.re-eat.recipe') stream = QDataStream(encodedData, QIODevice.ReadOnly) while not stream.atEnd(): id = stream.readInt() self.recipeAdded.emit(id, self.date, self.index) return True elif data.hasFormat('application/vnd.re-eat.meal_recipe'): encodedData = data.data('application/vnd.re-eat.meal_recipe') stream = QDataStream(encodedData, QIODevice.ReadOnly) while not stream.atEnd(): id = stream.readInt() date = stream.readQVariant() index = stream.readInt() self.recipeMoved.emit(id, date, index, self.date, self.index) return True return False
def mouseMoveEvent(self, event): if not (event.buttons() and Qt.LeftButton): return currentItem = self.currentItem() if(currentItem.isFile()): if(currentItem.isPic()): currentItemName = self.currentItem().getPath() data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) stream.writeQString(currentItemName) icon = Icons.image pixmap = icon.pixmap(64, 64) mimeData = QMimeData() mimeData.setText(currentItemName) mimeData.setData('application/x-item', data) drag = QDrag(self) drag.setPixmap(pixmap) drag.setHotSpot(QPoint(pixmap.width()/2, pixmap.height()/2)) drag.setMimeData(mimeData) dropAction = drag.start(Qt.CopyAction)
def test_dropping_the_data_emits_the_signal(self): rw = RecipesWidget() self.assertEqual(rw.supportedDropActions(), Qt.CopyAction | Qt.MoveAction) self.assertIn('application/vnd.re-eat.meal_recipe', rw.mimeTypes()) assert rw.viewport().acceptDrops() rw.recipeRemoved = DummySignal() mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) stream.writeInt(1) stream.writeQVariant(datetime.date.today()) stream.writeInt(2) mimeData.setData('application/vnd.re-eat.meal_recipe', encodedData) rw.dropMimeData(0, mimeData, Qt.CopyAction) self.assertListEqual(rw.recipeRemoved.received, [(1, datetime.date.today(), 2)])
def restoreState(self, state): """ Public method to restore the state of the sidebar. @param state byte array containing the saved state (QByteArray) @return flag indicating success (boolean) """ if state.isEmpty(): return False if self.__orientation in [E4SideBar.North, E4SideBar.South]: minSize = self.layout.minimumSize().height() maxSize = self.maximumHeight() else: minSize = self.layout.minimumSize().width() maxSize = self.maximumWidth() data = QByteArray(state) stream = QDataStream(data, QIODevice.ReadOnly) stream.readUInt16() # version minimized = stream.readBool() if minimized: self.shrink() stream >> self.__bigSize self.__minSize = max(stream.readUInt16(), minSize) self.__maxSize = max(stream.readUInt16(), maxSize) count = stream.readUInt16() self.splitterSizes = [] for i in range(count): self.splitterSizes.append(stream.readUInt16()) self.__autoHide = stream.readBool() self.__autoHideButton.setChecked(not self.__autoHide) if not minimized: self.expand() return True
def _onReadyRead(self): while self._socket.bytesAvailable() >= 4: ds = QDataStream(self._socket) ds.setByteOrder(QDataStream.LittleEndian) # Header packet if self.header is None: size, = unpack('=l', self._socket.peek(4)) if self._socket.bytesAvailable() < size + 4: return #Omit size ds.readUInt32() self.header = ds.readRawData(size).decode() # Chunks packet else: if self.nchunks == -1: self.nchunks = ds.readUInt32() self.chunks = [] while len(self.chunks) < self.nchunks: chunk = self._readLuaVal(ds) if chunk is None: return self.chunks.append(chunk) # Packet pair reading done. self._logger.info("GC >> : %s : %s", self.header, self.chunks) self.messageReceived.emit(self.header, self.chunks) self.header = None self.nchunks = -1 self.chunks = None
def test_dropping_the_data_emits_the_signal(self): rw = RecipesWidget() self.assertEqual(rw.supportedDropActions(), Qt.CopyAction|Qt.MoveAction) self.assertIn('application/vnd.re-eat.meal_recipe', rw.mimeTypes()) assert rw.viewport().acceptDrops() rw.recipeRemoved = DummySignal() mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) stream.writeInt(1) stream.writeQVariant(datetime.date.today()) stream.writeInt(2) mimeData.setData('application/vnd.re-eat.meal_recipe', encodedData) rw.dropMimeData(0, mimeData, Qt.CopyAction) self.assertListEqual(rw.recipeRemoved.received, [(1, datetime.date.today(), 2)])
def method_0(self, iwin32Window_0): if QFile.exists(FatoList.fileName): fl = QFile.remove(FatoList.fileName) f = open(FatoList.fileName, 'w') f.flush() f.close() else: f = open(FatoList.fileName, 'w') # f = open("D:/xml/phxasar.txt") f.flush() f.close() file0 = QFile(FatoList.fileName) file0.open(QIODevice.WriteOnly) dataStream = QDataStream(file0) dataStream.writeQString(QString("PHXHSAF")) dataStream.writeInt(1) dataStream.writeInt(len(self)) for fato in self: fato.method_6(dataStream) file0.flush() file0.close()
def ReadUserInfoFile(self): try: if not QFile.exists(self.m_strUserInfoFullName): return file0 = QFile(self.m_strUserInfoFullName) file0.open(QIODevice.ReadOnly) dataStream = QDataStream(file0) str0 = dataStream.readQString() self.m_strUserInfoFullName = dataStream.readQString() self.m_Key = dataStream.readQString() self.m_IV = dataStream.readQString() userInfoCount = dataStream.readInt() for i in range(userInfoCount): userInfo = MYUSERINFO() userInfo.readData(dataStream) self.ListUserInfo.append(userInfo) file0.close() return True except: return False
def changeResolution(self): fileName = QFileDialog.getOpenFileName(self, 'Load .prn file', directory=self.settings.value('unpacker/dir_open',QDir.currentPath()), filter='PRN files (*.prn *.bin);;All (*)') if not fileName: return file = QFile(fileName) if not file.open(QFile.ReadWrite): QMessageBox.warning(self, "Unpacker .prn", "Unable load file {}:\n{}.".format(fileName, file.errorString())) return self.settings.setValue('unpacker/dir_open', QFileInfo(file).path()) data = QDataStream(file) data.setByteOrder(QDataStream.LittleEndian) headerVersion = data.readInt32() xdpi = data.readInt32() ydpi = data.readInt32() dialog = ChangeResolutionDialog(xdpi, ydpi, self) if dialog.exec_(): file.seek(4) data.writeInt32(dialog.sbXdpi.value()) data.writeInt32(dialog.sbYdpi.value()) self.status.showMessage("Resolution changed successful", 7000) file.close()
def save(self): if self.filename.isEmpty(): path = "." fname = QFileDialog.getSaveFileName(self, "Page Designer - Save As", path, "Page Designer Files (*.pgd)") if fname.isEmpty(): return self.filename = fname fh = None try: fh = QFile(self.filename) if not fh.open(QIODevice.WriteOnly): raise IOError, unicode(fh.errorString()) self.scene.clearSelection() stream = QDataStream(fh) stream.setVersion(QDataStream.Qt_4_2) stream.writeInt32(MagicNumber) stream.writeInt16(FileVersion) for item in self.scene.items(): self.writeItemToStream(stream, item) except IOError, e: QMessageBox.warning(self, "Page Designer -- Save Error", "Failed to save {0}: {1}".format(self.filename, e))
def load(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError("no filename specified for loading") fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError(str(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 = QString() owner = QString() country = QString() description = QString() stream >> name >> owner >> country >> description teu = stream.readInt32() ship = Ship(name, owner, country, teu, description) self.ships[id(ship)] = ship self.owners.add(str(owner)) self.countries.add(str(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
def decode_data(self, bytearray): """Handle drag/drop data.""" 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
def WriteUserInfoFile(self): if QFile.exists(self.m_strUserInfoFullName): fl = QFile.remove(self.m_strUserInfoFullName) f = open(self.m_strUserInfoFullName, 'w') f.flush() f.close() else: f = open(self.m_strUserInfoFullName, 'w') # f = open("D:/xml/phxasar.txt") f.flush() f.close() file0 = QFile(self.m_strUserInfoFullName) file0.open(QIODevice.WriteOnly) dataStream = QDataStream(file0) dataStream.writeQString(QString("UserList")) dataStream.writeQString(QString(self.m_strUserInfoFullName)) dataStream.writeQString(QString(self.m_Key)) dataStream.writeQString(QString(self.m_IV)) dataStream.writeInt(len(self.ListUserInfo)) for userInfo in self.ListUserInfo: userInfo.writeData(dataStream) file0.flush() file0.close() return True
def send(self, command, *args): self._logger.info("GC<<: {}:{}".format(command, args)) ds = QDataStream(self._socket) ds.setByteOrder(QDataStream.LittleEndian) # Header ds.writeUInt32(len(command)) ds.writeRawData(command.encode()) # Chunks ds.writeUInt32(len(args)) for chunk in args: ds.writeRawData(self._packLuaVal(chunk))