【问题标题】:How can I add a bytearray image to QLabel in PyQt5如何在 PyQt5 中将字节数组图像添加到 QLabel
【发布时间】:2022-01-15 04:20:28
【问题描述】:

在本示例中,我正在从我的系统中导入图像,但我需要更清楚地了解如果我有一个 <class 'bytearray'> 我如何在我的 QLabel 中使用它?

from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
import sys


class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.acceptDrops()
        # set the title
        self.setWindowTitle("Image")

        # setting  the geometry of window
        self.setGeometry(0, 0, 400, 300)

        # creating label
        self.label = QLabel(self)

        # loading image locally
        self.pixmap = QPixmap('my_image.png')

        self.label.setScaledContents(True)

        # adding image to label
        self.label.setPixmap(self.pixmap)

        # show all the widgets
        self.show()


# create pyqt5 app
App = QApplication(sys.argv)

# create the instance of our Window
window = Window()

# start the app
sys.exit(App.exec())

如果我直接将<class 'bytearray'> 图像传递给QPixmap 它将不起作用并返回TypeError: QPixmap(): argument 1 has unexpected type 'bytearray'

【问题讨论】:

  • 你从哪里得到字节数组?在任何情况下,您都可以创建一个空的 QPixmap,然后使用loadFromData()self.pixmap = QPixmap()self.pixmap.loadFromData(QByteArray(data))。请注意,data 指的是字节数组 instance(包含字节数组的对象),而不是 bytearray (用于 创建一个实例)。

标签: arrays python-3.x pyqt pyqt5 qt5


【解决方案1】:

要首先使用bytearray 图像,您需要从QtCore 导入QByteArray 并将您的bytearray 传递给QByteArray,这是您可以遵循的方法。

from PyQt5.QtCore import QByteArray
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
import sys

from temp2 import my_img


class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.acceptDrops()
        # set the title
        self.setWindowTitle("Image")

        # setting  the geometry of window
        self.setGeometry(0, 0, 400, 300)

        # creating label
        self.label = QLabel(self)
        self.pixmap = QPixmap()
        self.pixmap.loadFromData(QByteArray(my_img()))

        # # loading image locally
        # self.pixmap = QPixmap(my_img())

        self.label.setScaledContents(True)

        # adding image to label
        self.label.setPixmap(self.pixmap)

        # show all the widgets
        self.show()


# create pyqt5 app
App = QApplication(sys.argv)

# create the instance of our Window
window = Window()

# start the app
sys.exit(App.exec())

【讨论】:

  • omg 非常感谢它确实有效:D
猜你喜欢
  • 1970-01-01
  • 2016-09-10
  • 2018-05-31
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 2013-08-17
相关资源
最近更新 更多