Python PyQt5.QtCore.QByteArray() Examples

The following are 30 code examples for showing how to use PyQt5.QtCore.QByteArray(). 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: hae   Author: Lanfei   File: window.py    License: MIT License 7 votes vote down vote up
def capture(self, fullScreen = False, filename = ''):
		if fullScreen:
			image = QApplication.primaryScreen().grabWindow(0)
		else:
			image = QImage(self.webView.mainFrame.contentsSize(), QImage.Format_ARGB32)
			painter = QPainter(image)
			self.webView.mainFrame.render(painter)
			painter.end()
		if filename:
			return image.save(filename)
		else:
			data = QByteArray()
			buffer = QBuffer(data)
			buffer.open(QBuffer.WriteOnly)
			image.save(buffer, 'PNG')
			return bytes(data.toBase64()).decode()

	# 打开开发者工具 
Example 2
Project: Lector   Author: BasioMeusPuga   File: sorter.py    License: GNU General Public License v3.0 6 votes vote down vote up
def resize_image(cover_image_raw):
    if isinstance(cover_image_raw, QtGui.QImage):
        cover_image = cover_image_raw
    else:
        cover_image = QtGui.QImage()
        cover_image.loadFromData(cover_image_raw)

    # Resize image to what literally everyone
    # agrees is an acceptable cover size
    cover_image = cover_image.scaled(
        420, 600, QtCore.Qt.IgnoreAspectRatio)

    byte_array = QtCore.QByteArray()
    buffer = QtCore.QBuffer(byte_array)
    buffer.open(QtCore.QIODevice.WriteOnly)
    cover_image.save(buffer, 'jpg', 75)

    cover_image_final = io.BytesIO(byte_array)
    cover_image_final.seek(0)
    return cover_image_final.getvalue() 
Example 3
Project: Cura   Author: Ultimaker   File: NetworkMJPGImage.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self._stream_buffer = QByteArray()
        self._stream_buffer_start_index = -1
        self._network_manager = None  # type: QNetworkAccessManager
        self._image_request = None  # type: QNetworkRequest
        self._image_reply = None  # type: QNetworkReply
        self._image = QImage()
        self._image_rect = QRect()

        self._source_url = QUrl()
        self._started = False

        self._mirror = False

        self.setAntialiasing(True) 
Example 4
Project: Cura   Author: Ultimaker   File: NetworkMJPGImage.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def stop(self) -> None:
        self._stream_buffer = QByteArray()
        self._stream_buffer_start_index = -1

        if self._image_reply:
            try:
                try:
                    self._image_reply.downloadProgress.disconnect(self._onStreamDownloadProgress)
                except Exception:
                    pass

                if not self._image_reply.isFinished():
                    self._image_reply.close()
            except Exception:  # RuntimeError
                pass  # It can happen that the wrapped c++ object is already deleted.

            self._image_reply = None
            self._image_request = None

        self._network_manager = None

        self._started = False 
Example 5
Project: imperialism-remake   Author: Trilarion   File: network.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 6
Project: imperialism-remake   Author: Trilarion   File: network.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 7
Project: pychemqt   Author: jjgomera   File: widgets.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 8
Project: Miyamoto   Author: aboood40091   File: items.py    License: GNU General Public License v3.0 6 votes vote down vote up
def UpdateListItem(self, updateTooltipPreview=False):
        """
        Updates the list item
        """
        if not hasattr(self, 'listitem'): return
        if self.listitem is None: return

        if updateTooltipPreview:
            # It's just like Qt to make this overly complicated. XP
            img = self.renderInLevelIcon()
            byteArray = QtCore.QByteArray()
            buf = QtCore.QBuffer(byteArray)
            img.save(buf, 'PNG')
            byteObj = bytes(byteArray)
            b64 = base64.b64encode(byteObj).decode('utf-8')

            self.listitem.setToolTip('<img src="data:image/png;base64,' + b64 + '" />')

        self.listitem.setText(self.ListString()) 
Example 9
Project: PyQt   Author: PyQt5   File: DynamicRes.py    License: GNU General Public License v3.0 6 votes vote down vote up
def loadResource(self, rtype, url):
        ret = super(TextBrowser, self).loadResource(rtype, url)
        # 加载图片资源
        if rtype == QTextDocument.ImageResource:
            if ret:
                return ret
            if url.toString().startswith('irony'):  # 自定义的协议头
                print('加载本地', '../Donate/zhifubao.png', url)
                return QImage('../Donate/zhifubao.png')  # 或者 QByteArray(open('../Donate/zhifubao.png', 'rb').read())
            elif url.toString().startswith('http'):  # 加载网络图片
                img, status = self.NetImages.get(url, [None, None])
                if url not in self.NetImages or status is None:
                    # 子线程下载
                    self.NetImages[url] = [None, 1]
                    print('download ', url)
                    Thread(target=self.downloadImage, args=(url,), daemon=True).start()
                elif img:
                    return img
        return ret 
Example 10
def stop(self) -> None:
        Logger.log("w", "MJPEG stopping stream...")	
        self._stream_buffer = QByteArray()
        self._stream_buffer_start_index = -1

        if self._image_reply:
            try:
                try:
                    self._image_reply.downloadProgress.disconnect(self._onStreamDownloadProgress)
                except Exception:
                    pass

                if not self._image_reply.isFinished():
                    self._image_reply.close()
            except Exception as e:  # RuntimeError
                pass  # It can happen that the wrapped c++ object is already deleted.

            self._image_reply = None
            self._image_request = None

        self._network_manager = None

        self._started = False 
Example 11
Project: kw_condition   Author: coreanq   File: pandasmodel.py    License: MIT License 5 votes vote down vote up
def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid():
            if(role==QtCore.Qt.DisplayRole):
                return self._data.values[index.row()][index.column()]
            else:
                # self._roleName 은 QHash(int, QByteArray)
                columnName = self._roleNames[role].data().decode('utf8')
                print('row {} col {} role {} columnName {} '.format(index.row(), index.column(), role, columnName))
                print(self._data.at[index.row(), columnName])
                return self._data.at[index.row(), columnName]
        return QVariant() 
Example 12
Project: kw_condition   Author: coreanq   File: pandasmodel.py    License: MIT License 5 votes vote down vote up
def headerData(self, col, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return self._data.columns[col]
        return None
        
    # return 값은 QHash(int, QByteArray) 
Example 13
Project: kw_condition   Author: coreanq   File: pandasmodel.py    License: MIT License 5 votes vote down vote up
def roleNames(self):
        for index, name in enumerate(self._data.columns):
            self._roleNames[ QtCore.Qt.UserRole + index + 1] = QtCore.QByteArray(name.encode())
        return self._roleNames 
Example 14
Project: qutebrowser   Author: qutebrowser   File: test_sessions.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, geometry, win_id, parent=None):
        super().__init__(parent)
        self._geometry = QByteArray(geometry)
        self.win_id = win_id 
Example 15
Project: uPyLoader   Author: BetaRavener   File: settings.py    License: MIT License 5 votes vote down vote up
def retrieve_geometry(self, name):
        if name not in self._geometries:
            return None

        return QByteArray(bytes(self._geometries[name])) 
Example 16
Project: ddt4all   Author: cedricp   File: displaymod.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_zip_graphic(self, name):
        if os.path.exists("ecu.zip"):
            zf = zipfile.ZipFile("ecu.zip", "r")
            zname = "graphics/" + name + ".gif"
            if not zname in zf.namelist():
                zname = "graphics/" + name + ".GIF"
            if zname in zf.namelist():
                ba = core.QByteArray(zf.read(zname))
                self.buffer = core.QBuffer()
                self.buffer.setData(ba)
                self.buffer.open(core.QIODevice.ReadOnly)
                self.img = gui.QMovie(self.buffer, 'GIF') 
Example 17
Project: scudcloud   Author: raelgc   File: wrapper.py    License: MIT License 5 votes vote down vote up
def pasted(self, checked):
        clipboard = QApplication.clipboard()
        mime = clipboard.mimeData()
        if mime.hasImage():
            pixmap = clipboard.pixmap()
            byteArray = QByteArray()
            buffer = QBuffer(byteArray)
            pixmap.save(buffer, "PNG")
            self.call("setClipboard", str(byteArray.toBase64(), sys.stdout.encoding)) 
Example 18
Project: scudcloud   Author: raelgc   File: cookiejar.py    License: MIT License 5 votes vote down vote up
def save(self):
        listCookies = self.allCookies()
        data = QtCore.QByteArray()
        for cookie in listCookies:
            if not cookie.isSessionCookie():
                data.append(cookie.toRawForm().append("\n"))
        self.mainWindow.settings.setValue("Cookies",data) 
Example 19
Project: Miyamoto   Author: aboood40091   File: misc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setting(name, default=None):
    """
    Thin wrapper around QSettings, fixes the type=bool bug
    """
    types_str = {str: 'str', int: 'int', float: 'float', dict: 'dict', bool: 'bool', QtCore.QByteArray: 'QByteArray', type(None): 'NoneType'}
    types = {'str': str, 'int': int, 'float': float, 'dict': dict, 'bool': bool, 'QByteArray': QtCore.QByteArray}

    type_ = globals.settings.value('typeof(%s)' % name, types_str[type(default)], str)
    if type_ == 'NoneType':
        return None

    return globals.settings.value(name, default, types[type_]) 
Example 20
Project: Miyamoto   Author: aboood40091   File: misc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setSetting(name, value):
    """
    Thin wrapper around QSettings
    """
    types_str = {str: 'str', int: 'int', float: 'float', dict: 'dict', bool: 'bool', QtCore.QByteArray: 'QByteArray', type(None): 'NoneType'}
    assert isinstance(name, str) and type(value) in types_str

    globals.settings.setValue(name, value)
    globals.settings.setValue('typeof(%s)' % name, types_str[type(value)]) 
Example 21
Project: Miyamoto   Author: aboood40091   File: puzzle.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 22
Project: eddy   Author: danielepantaleone   File: session.py    License: GNU General Public License v3.0 5 votes vote down vote up
def initState(self):
        """
        Configure application state by reading the preferences file.
        """
        settings = QtCore.QSettings(ORGANIZATION, APPNAME)
        self.restoreGeometry(settings.value('session/geometry', QtCore.QByteArray(), QtCore.QByteArray))
        self.restoreState(settings.value('session/state', QtCore.QByteArray(), QtCore.QByteArray))
        self.action('toggle_grid').setChecked(settings.value('diagram/grid', False, bool)) 
Example 23
Project: pyNMS   Author: afourmy   File: site_panel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def mousePressEvent(self, event):
        # retrieve the label 
        child = self.childAt(event.pos())
        
        if not child:
            return
        
        self.controller.mode = 'selection'
        # update the creation mode to the appropriate subtype
        self.controller.creation_mode = child.subtype
        
        pixmap = QPixmap(child.pixmap().scaled(
                                            QSize(50, 50), 
                                            Qt.KeepAspectRatio,
                                            Qt.SmoothTransformation
                                            ))

        mime_data = QtCore.QMimeData()
        mime_data.setData('application/x-dnditemdata', QtCore.QByteArray())

        drag = QtGui.QDrag(self)
        drag.setMimeData(mime_data)
        drag.setPixmap(pixmap)
        drag.setHotSpot(event.pos() - child.pos() + QPoint(-3, -10))

        if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction:
            child.close()
        else:
            child.show() 
Example 24
Project: pyNMS   Author: afourmy   File: internal_node_creation_panel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def mousePressEvent(self, event):
        # retrieve the label 
        child = self.childAt(event.pos())
        
        if not child:
            return
        
        self.controller.mode = 'selection'
        # update the creation mode to the appropriate subtype
        self.controller.creation_mode = child.subtype
        
        pixmap = QPixmap(child.pixmap().scaled(
                                            QSize(50, 50), 
                                            Qt.KeepAspectRatio,
                                            Qt.SmoothTransformation
                                            ))

        mime_data = QtCore.QMimeData()
        mime_data.setData('application/x-dnditemdata', QtCore.QByteArray())

        drag = QtGui.QDrag(self)
        drag.setMimeData(mime_data)
        drag.setPixmap(pixmap)
        drag.setHotSpot(event.pos() - child.pos() + QPoint(-3, -10))

        if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction:
            child.close()
        else:
            child.show() 
Example 25
Project: pyNMS   Author: afourmy   File: network_node_creation_panel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def mousePressEvent(self, event):
        # retrieve the label 
        child = self.childAt(event.pos())
        if not child:
            return
        
        self.controller.mode = 'selection'
        # update the creation mode to the appropriate subtype
        self.controller.creation_mode = child.subtype
        # we change the view if necessary:
        # if it is a site, we switch the site view
        # if it is anything else and we are in the site view, we switch 
        # to the network view
        if child.subtype == 'site':
            self.project.show_site_view()
        else:
            if self.project.view_type == 'site':
                self.project.show_network_view()
        
        pixmap = QPixmap(child.pixmap().scaled(
                                            QSize(50, 50), 
                                            Qt.KeepAspectRatio,
                                            Qt.SmoothTransformation
                                            ))

        mime_data = QtCore.QMimeData()
        mime_data.setData('application/x-dnditemdata', QtCore.QByteArray())

        drag = QtGui.QDrag(self)
        drag.setMimeData(mime_data)
        drag.setPixmap(pixmap)
        drag.setHotSpot(event.pos() - child.pos() + QPoint(-3, -10))

        if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction:
            child.close()
        else:
            child.show() 
Example 26
Project: Mastering-GUI-Programming-with-Python   Author: PacktPublishing   File: udp_chat.py    License: MIT License 5 votes vote down vote up
def process_datagrams(self):
        while self.socket.hasPendingDatagrams():
            datagram = self.socket.receiveDatagram()
            # to convert QByteArray to a string,
            # cast it to bytes then decode
            raw_message = bytes(datagram.data()).decode('utf-8')

            if self.delimiter not in raw_message:
                # invalid message, ignore
                continue
            username, message = raw_message.split(self.delimiter, 1)
            self.received.emit(username, message) 
Example 27
Project: Mastering-GUI-Programming-with-Python   Author: PacktPublishing   File: udp_chat.py    License: MIT License 5 votes vote down vote up
def send_message(self, message):
        """Prepare and send a message"""
        msg_bytes = (
            f'{self.username}{self.delimiter}{message}'
            ).encode('utf-8')
        self.socket.writeDatagram(
            qtc.QByteArray(msg_bytes),
            qtn.QHostAddress.Broadcast,
            self.port
            ) 
Example 28
Project: PyQt   Author: PyQt5   File: GetCookie.py    License: GNU General Public License v3.0 5 votes vote down vote up
def bytestostr(self, data):
        if isinstance(data, str):
            return data
        if isinstance(data, QByteArray):
            data = data.data()
        if isinstance(data, bytes):
            data = data.decode(errors='ignore')
        else:
            data = str(data)
        return data 
Example 29
Project: PyQt   Author: PyQt5   File: SerialDebugAssistant.py    License: GNU General Public License v3.0 5 votes vote down vote up
def on_buttonSend_clicked(self):
        # 发送消息按钮
        if not self._serial.isOpen():
            print('串口未连接')
            return
        text = self.plainTextEdit.toPlainText()
        if not text:
            return
        text = QByteArray(text.encode('gb2312'))  # emmm windows 测试的工具貌似是这个编码
        if self.checkBoxHexSend.isChecked():
            # 如果勾选了hex发送
            text = text.toHex()
        # 发送数据
        print('发送数据:', text)
        self._serial.write(text) 
Example 30
Project: PyQt   Author: PyQt5   File: DynamicRes.py    License: GNU General Public License v3.0 5 votes vote down vote up
def downloadImage(self, url):
        try:
            self.NetImages[url] = [QByteArray(requests.get(url.toString()).content), 1]
            print('下载完成', url)
        except Exception as e:
            print('下载失败', url, e)
            self.NetImages[url] = [QByteArray(), 1]