當前位置: 首頁>>代碼示例>>Python>>正文


Python QtCore.QDataStream方法代碼示例

本文整理匯總了Python中PyQt5.QtCore.QDataStream方法的典型用法代碼示例。如果您正苦於以下問題:Python QtCore.QDataStream方法的具體用法?Python QtCore.QDataStream怎麽用?Python QtCore.QDataStream使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在PyQt5.QtCore的用法示例。


在下文中一共展示了QtCore.QDataStream方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _receive

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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) 
開發者ID:Trilarion,項目名稱:imperialism-remake,代碼行數:27,代碼來源:network.py

示例2: send

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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 
開發者ID:Trilarion,項目名稱:imperialism-remake,代碼行數:27,代碼來源:network.py

示例3: __init__

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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) 
開發者ID:jjgomera,項目名稱:pychemqt,代碼行數:23,代碼來源:widgets.py

示例4: closeEvent

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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() 
開發者ID:jjgomera,項目名稱:pychemqt,代碼行數:32,代碼來源:flujo.py

示例5: copy

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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) 
開發者ID:jjgomera,項目名稱:pychemqt,代碼行數:9,代碼來源:flujo.py

示例6: paste

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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) 
開發者ID:jjgomera,項目名稱:pychemqt,代碼行數:11,代碼來源:flujo.py

示例7: mimeData

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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 
開發者ID:aboood40091,項目名稱:Miyamoto,代碼行數:15,代碼來源:puzzle.py

示例8: switch_language

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:39,代碼來源:lang.py

示例9: process_datastream

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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) 
開發者ID:PacktPublishing,項目名稱:Mastering-GUI-Programming-with-Python,代碼行數:12,代碼來源:tcp_chat.py

示例10: send_message

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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) 
開發者ID:PacktPublishing,項目名稱:Mastering-GUI-Programming-with-Python,代碼行數:13,代碼來源:tcp_chat.py

示例11: process_datastream

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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() 
開發者ID:PacktPublishing,項目名稱:Mastering-GUI-Programming-with-Python,代碼行數:8,代碼來源:question_3_tcp_server.py

示例12: serialize

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:44,代碼來源:tabhistory.py

示例13: serialize

# 需要導入模塊: from PyQt5 import QtCore [as 別名]
# 或者: from PyQt5.QtCore import QDataStream [as 別名]
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 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:53,代碼來源:tabhistory.py


注:本文中的PyQt5.QtCore.QDataStream方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。