Python PyQt5.QtCore.QByteArray() Examples

The following are 30 code examples of PyQt5.QtCore.QByteArray(). 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 also want to check out all available functions/classes of the module PyQt5.QtCore , or try the search function .
Example #1
Source File: window.py    From hae with MIT License 8 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
Source File: sorter.py    From Lector with GNU General Public License v3.0 7 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
Source File: NetworkMJPGImage.py    From RepetierIntegration with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #4
Source File: NetworkMJPGImage.py    From Cura with 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
Source File: network.py    From imperialism-remake with 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
Source File: network.py    From imperialism-remake with 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
Source File: DynamicRes.py    From PyQt with 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 #8
Source File: items.py    From Miyamoto with 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
Source File: widgets.py    From pychemqt with 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 #10
Source File: internal_node_creation_panel.py    From pyNMS with 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 #11
Source File: pandasmodel.py    From kw_condition with 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 #12
Source File: network_node_creation_panel.py    From pyNMS with 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 #13
Source File: udp_chat.py    From Mastering-GUI-Programming-with-Python with 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 #14
Source File: udp_chat.py    From Mastering-GUI-Programming-with-Python with 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 #15
Source File: GetCookie.py    From PyQt with 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 #16
Source File: SerialDebugAssistant.py    From PyQt with 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 #17
Source File: DynamicRes.py    From PyQt with 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] 
Example #18
Source File: GetCookie.py    From PyQt with 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 #19
Source File: ble.py    From artisan with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,service_uuid, char_uuid, processData, sendHeartbeat, sendStop, reset):
        super().__init__()
        
#        cp = QtBluetooth.QLowEnergyConnectionParameters()
#        print("max interval",cp.maximumInterval())
#        print("min interval",cp.minimumInterval())
#        print("supervisionTimeout",cp.supervisionTimeout())
#        print("latency()",cp.latency())
        
        self.SERVICE_UUID = QtBluetooth.QBluetoothUuid(service_uuid)
        self.CHAR_UUID = QtBluetooth.QBluetoothUuid(char_uuid)
        self.processData = processData
        self.sendHeartbeat = sendHeartbeat
        self.sendStop = sendStop
        self.reset = reset
        
        self.QBluetoothDeviceDiscoveryAgent_LowEnergyMethod = 2
        self.ENABLE_NOTIFICATION_VALUE = QtCore.QByteArray.fromHex(b"0100")
        self.DISABLE_NOTIFICATION_VALUE = QtCore.QByteArray.fromHex(b"0000")

        self.m_deviceDiscoveryAgent = QtBluetooth.QBluetoothDeviceDiscoveryAgent()
        self.m_deviceDiscoveryAgent.setLowEnergyDiscoveryTimeout(500)
        self.m_deviceDiscoveryAgent.deviceDiscovered.connect(self.addDevice)
        self.m_deviceDiscoveryAgent.finished.connect(self.onScanFinished)
        self.m_deviceDiscoveryAgent.canceled.connect(self.onScanFinished)

        self.m_device = None
        self.m_control = None
        self.m_service = None

        self.m_notificationDesc = QtBluetooth.QLowEnergyDescriptor()
        self.m_readCharacteristic = QtBluetooth.QLowEnergyCharacteristic()
        self.m_writeCharacteristic = QtBluetooth.QLowEnergyCharacteristic()
        self.m_writemode = QtBluetooth.QLowEnergyService.WriteMode()

        self.m_connected = False
        self.m_readTimer = None
        
        self.dataReceived.connect(self.printDataReceived) 
Example #20
Source File: ble.py    From artisan with GNU General Public License v3.0 5 votes vote down vote up
def printDataReceived(self,data=QtCore.QByteArray):
#        print("received data:{data}".format(data =data))
        res_w, res_b = self.processData(self.write, data)
        if res_w is not None:
            self.weightChanged.emit(res_w)
        if res_b is not None:
            self.batteryChanged.emit(res_b) 
Example #21
Source File: ble.py    From artisan with GNU General Public License v3.0 5 votes vote down vote up
def onCharacteristicChanged(self,_=QtBluetooth.QLowEnergyCharacteristic,value=QtCore.QByteArray):
#        print("Characteristic Changed {values}".format(values=value))
        self.dataReceived.emit(value) 
Example #22
Source File: ble.py    From artisan with GNU General Public License v3.0 5 votes vote down vote up
def onCharacteristicRead(self,_=QtBluetooth.QLowEnergyCharacteristic,value=QtCore.QByteArray):
#        print("Characteristic Read:  {values}".format(values=value))
        pass 
Example #23
Source File: NetworkMJPGImage.py    From RepetierIntegration with GNU Affero General Public License v3.0 5 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)

    ##  Ensure that close gets called when object is destroyed 
Example #24
Source File: tree_numeric.py    From asammdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def startDrag(self, supportedActions):
        selected_items = self.selectedItems()

        mimeData = QtCore.QMimeData()

        data = []

        for item in selected_items:

            entry = item.entry

            if entry == (-1, -1):
                info = {
                    "name": item.name,
                    "computation": {},
                }
                info = json.dumps(info).encode("utf-8")
            else:
                info = item.name.encode("utf-8")

            data.append(
                pack(
                    f"<36s3q{len(info)}s",
                    str(item.mdf_uuid).encode("ascii"),
                    entry[0],
                    entry[1],
                    len(info),
                    info,
                )
            )

        mimeData.setData(
            "application/octet-stream-asammdf", QtCore.QByteArray(b"".join(data))
        )

        drag = QtGui.QDrag(self)
        drag.setMimeData(mimeData)
        drag.exec(QtCore.Qt.CopyAction) 
Example #25
Source File: wrapper.py    From scudcloud with 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 #26
Source File: pandasmodel.py    From kw_condition with 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 #27
Source File: pandasmodel.py    From kw_condition with 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 #28
Source File: test_sessions.py    From qutebrowser with 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 #29
Source File: settings.py    From uPyLoader with 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 #30
Source File: NetworkMJPGImage.py    From Cura with GNU Lesser General Public License v3.0 5 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)