Python PyQt5.QtCore.QDataStream() Examples
The following are 13 code examples for showing how to use PyQt5.QtCore.QDataStream(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
PyQt5.QtCore
, or try the search function
.
Example 1
Project: imperialism-remake Author: Trilarion File: network.py License: GNU General Public License v3.0 | 6 votes |
def _receive(self): """ Called by the sockets readyRead signal. Not intended for outside use. While there are messages available read them and process them. Reading is reading of a QByteArray from the TCPSocket, un-compressing and de-serializing. """ while self.socket.bytesAvailable() > 0: logger.info('socket will receive') # read a QByteArray using a data stream reader = QtCore.QDataStream(self.socket) bytearray = QtCore.QByteArray() reader >> bytearray # uncompress bytes from bytearray uncompressed = zlib.decompress(bytearray.data()) # security validator (check for everything that we do not like (!!python) # TODO implement this # decode from utf-8 bytes to unicode and deserialize from yaml value = yaml.load(uncompressed.decode()) logger.debug('socket received: %s', value) self.received.emit(value)
Example 2
Project: imperialism-remake Author: Trilarion File: network.py License: GNU General Public License v3.0 | 6 votes |
def send(self, value): """ Sends a message by serializing, compressing and wrapping to a QByteArray, then streaming over the TCP socket. :param value: The message to send. """ if not self.is_connected(): raise RuntimeError('Try to send on unconnected socket.') logger.debug('socket send: %s', value) # serialize value to yaml stream = StringIO() yaml.dump(value, stream) serialized = stream.getvalue() # encode to utf-8 bytes and compress compressed = zlib.compress(serialized.encode()) # wrap in QByteArray bytearray = QtCore.QByteArray(compressed) # write using a data stream writer = QtCore.QDataStream(self.socket) writer.setVersion(QtCore.QDataStream.Qt_5_5) writer << bytearray
Example 3
Project: pychemqt Author: jjgomera File: widgets.py License: GNU General Public License v3.0 | 6 votes |
def __init__(self, parent=None): super(DragButton, self).__init__(parent) # def mouseMoveEvent(self, event): # self.startDrag() # QtWidgets.QToolButton.mouseMoveEvent(self, event) # def startDrag(self): # if self.icon().isNull(): # return # data = QtCore.QByteArray() # stream = QtCore.QDataStream(data, QtCore.QIODevice.WriteOnly) # stream << self.icon() # mimeData = QtCore.QMimeData() # mimeData.setData("application/x-equipment", data) # drag = QtGui.QDrag(self) # drag.setMimeData(mimeData) # pixmap = self.icon().pixmap(24, 24) # drag.setHotSpot(QtCore.QPoint(12, 12)) # drag.setPixmap(pixmap) # drag.exec_(QtCore.Qt.CopyAction)
Example 4
Project: pychemqt Author: jjgomera File: flujo.py License: GNU General Public License v3.0 | 5 votes |
def closeEvent(self, event): if self.PFD: event.ignore() # def dragEnterEvent(self, event): # if event.mimeData().hasFormat("application/x-equipment"): # event.accept() # else: # event.ignore() # def dragMoveEvent(self, event): # if event.mimeData().hasFormat("application/x-equipment"): # event.setDropAction(QtCore.Qt.CopyAction) # event.accept() # else: # event.ignore() # def dropEvent(self, event): # if event.mimeData().hasFormat("application/x-equipment"): # data = event.mimeData().data("application/x-equipment") # stream = QtCore.QDataStream(data, QtCore.QIODevice.ReadOnly) # icon = QtGui.QIcon() # stream >> icon # event.setDropAction(QtCore.Qt.CopyAction) # print(event.pos()) # event.accept() # self.updateGeometry() # self.update() # else: # event.ignore()
Example 5
Project: pychemqt Author: jjgomera File: flujo.py License: GNU General Public License v3.0 | 5 votes |
def copy(self, item=None): if not item: item = self.selectedItems()[0] self.copiedItem.clear() self.pasteOffset = 5 stream = QtCore.QDataStream(self.copiedItem, QtCore.QIODevice.WriteOnly) self.writeItemToStream(stream, item)
Example 6
Project: pychemqt Author: jjgomera File: flujo.py License: GNU General Public License v3.0 | 5 votes |
def paste(self, pos=None): stream = QtCore.QDataStream(self.copiedItem, QtCore.QIODevice.ReadOnly) item = self.readItemFromStream(stream) if pos: item.setPos(pos) else: item.setPos(item.pos() + QtCore.QPointF(self.pasteOffset, self.pasteOffset)) self.pasteOffset += 5 self.addItem(item)
Example 7
Project: Miyamoto Author: aboood40091 File: puzzle.py License: GNU General Public License v3.0 | 5 votes |
def mimeData(self, indexes): mimeData = QtCore.QMimeData() encodedData = QtCore.QByteArray() stream = QtCore.QDataStream(encodedData, QtCore.QIODevice.WriteOnly) for index in indexes: if index.isValid(): pixmap = QtGui.QPixmap(self.data(index, Qt.UserRole)) stream << pixmap mimeData.setData('image/x-tile-piece', encodedData) return mimeData
Example 8
Project: parsec-cloud Author: Scille File: lang.py License: GNU Affero General Public License v3.0 | 5 votes |
def switch_language(core_config, lang_key=None): global _current_translator global _current_locale_language QCoreApplication.translate = qt_translate if not lang_key: lang_key = core_config.gui_language if not lang_key: lang_key = get_locale_language() logger.info(f"No language in settings, trying local language '{lang_key}'") if lang_key not in LANGUAGES.values(): if lang_key != "en": logger.info(f"Language '{lang_key}' unavailable, defaulting to English") lang_key = "en" _current_locale_language = lang_key rc_file = QFile(f":/translations/translations/parsec_{lang_key}.mo") if not rc_file.open(QIODevice.ReadOnly): logger.warning(f"Unable to read the translations for language '{lang_key}'") return None try: data_stream = QDataStream(rc_file) out_stream = io.BytesIO() content = data_stream.readRawData(rc_file.size()) out_stream.write(content) out_stream.seek(0) _current_translator = gettext.GNUTranslations(out_stream) _current_translator.install() except OSError: logger.warning(f"Unable to load the translations for language '{lang_key}'") return None finally: rc_file.close() return lang_key
Example 9
Project: Mastering-GUI-Programming-with-Python Author: PacktPublishing File: tcp_chat.py License: MIT License | 5 votes |
def process_datastream(self): for socket in self.connections: self.datastream = qtc.QDataStream(socket) if not socket.bytesAvailable(): continue #message_length = self.datastream.readUInt32() raw_message = self.datastream.readQString() if raw_message and self.delimiter in raw_message: username, message = raw_message.split(self.delimiter, 1) self.received.emit(username, message)
Example 10
Project: Mastering-GUI-Programming-with-Python Author: PacktPublishing File: tcp_chat.py License: MIT License | 5 votes |
def send_message(self, message): """Prepare and send a message""" raw_message = f'{self.username}{self.delimiter}{message}' if self.client_socket.state() != qtn.QAbstractSocket.ConnectedState: self.client_socket.connectToHost(self.recipient, self.port) self.datastream = qtc.QDataStream(self.client_socket) #self.datastream.writeUInt32() self.datastream.writeQString(raw_message) # Echo locally self.received.emit(self.username, message)
Example 11
Project: Mastering-GUI-Programming-with-Python Author: PacktPublishing File: question_3_tcp_server.py License: MIT License | 5 votes |
def process_datastream(self): for cx in self.connections: self.datastream = qtc.QDataStream(cx) print(self.datastream.readRawData(cx.bytesAvailable())) self.datastream.writeRawData(b'PyQt5 Rocks!') cx.disconnectFromHost()
Example 12
Project: qutebrowser Author: qutebrowser File: tabhistory.py License: GNU General Public License v3.0 | 4 votes |
def serialize(items): """Serialize a list of WebHistoryItems to a data stream. Args: items: An iterable of WebHistoryItems. Return: A (stream, data, user_data) tuple. stream: The reset QDataStream. data: The QByteArray with the raw data. user_data: A list with each item's user data. Warning: If 'data' goes out of scope, reading from 'stream' will result in a segfault! """ data = QByteArray() stream = QDataStream(data, QIODevice.ReadWrite) user_data = [] # type: typing.List[typing.Mapping[str, typing.Any]] current_idx = None for i, item in enumerate(items): if item.active: if current_idx is not None: raise ValueError("Multiple active items ({} and {}) " "found!".format(current_idx, i)) current_idx = i if items: if current_idx is None: raise ValueError("No active item found!") else: current_idx = 0 _serialize_items(items, current_idx, stream) user_data += [item.user_data for item in items] stream.device().reset() qtutils.check_qdatastream(stream) return stream, data, user_data
Example 13
Project: qutebrowser Author: qutebrowser File: tabhistory.py License: GNU General Public License v3.0 | 4 votes |
def serialize(items): """Serialize a list of WebHistoryItems to a data stream. Args: items: An iterable of WebHistoryItems. Return: A (stream, data, user_data) tuple. stream: The reset QDataStream. data: The QByteArray with the raw data. cur_user_data: The user data for the current item or None. Warning: If 'data' goes out of scope, reading from 'stream' will result in a segfault! """ data = QByteArray() stream = QDataStream(data, QIODevice.ReadWrite) cur_user_data = None current_idx = None for i, item in enumerate(items): if item.active: if current_idx is not None: raise ValueError("Multiple active items ({} and {}) " "found!".format(current_idx, i)) current_idx = i cur_user_data = item.user_data if items: if current_idx is None: raise ValueError("No active item found!") else: current_idx = -1 ### src/core/web_contents_adapter.cpp serializeNavigationHistory # sample data: # kHistoryStreamVersion stream.writeInt(HISTORY_STREAM_VERSION) # \x00\x00\x00\x03 # count stream.writeInt(len(items)) # \x00\x00\x00\x01 # currentIndex stream.writeInt(current_idx) # \x00\x00\x00\x00 for item in items: _serialize_item(item, stream) stream.device().reset() qtutils.check_qdatastream(stream) return stream, data, cur_user_data