【问题标题】:QPixmap and GUI threadingQPixmap 和 GUI 线程
【发布时间】:2018-09-14 17:40:53
【问题描述】:

我正在尝试启动并运行一个小示例,其中一个线程执行屏幕截图并将其发送到要显示的 GUI 应用程序。但我收到了这个“错误”

QPixmap: It is not safe to use pixmaps outside the GUI thread

我已经尝试阅读,但很难理解为什么它给我这个,因为 QImage 是在主应用程序和 GUI 线程中创建的?

我希望我的标签显示线程捕获的图像。

class Main(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 280, 600)
        self.layout = QtGui.QVBoxLayout(self)

        self.testButton = QtGui.QPushButton("Click Me")
        self.connect(self.testButton, QtCore.SIGNAL("clicked()"), self.Capture)

        self.layout.addWidget(self.testButton)

        self.label_ = QLabel(self)
        self.label_.move(280, 120)
        self.label_.resize(640, 480)
        self.layout.addWidget(self.label_)


    @pyqtSlot(QImage) 
    def ChangeFrame(self, image):  
        qimg = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888)

        self.label_.setPixmap(QPixmap.fromImage(qimg))


    def Capture(self):       
        self.thread_ = CaptureScreen()        
        self.connect(self.thread_, QtCore.SIGNAL("ChangeFrame(PyQt_PyObject)"), self.ChangeFrame, Qt.DirectConnection)
        self.thread_.start()       

class CaptureScreen(QtCore.QThread):
    pixmap = pyqtSignal(QImage)

    def __del__(self):
        self.exiting = True
        self.wait()

    def run(self):    
        img = ImageGrab.grab(bbox=(100,10,400,780))
        img_np = np.array(img)
        frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)        

        self.emit( QtCore.SIGNAL("ChangeFrame(PyQt_PyObject)"), frame)



app = QtGui.QApplication(sys.argv)
test = Main()
test.show()
app.exec_()

【问题讨论】:

    标签: python pyqt pyqt4


    【解决方案1】:

    来自the docs

    Direct Connection 当信号发出时,槽会立即被调用。槽在发射器的线程中执行,不一定是接收器的线程。

    通过在连接信号时指定Qt.DirectConnection,您将导致CaptureScreen 线程调用connected 方法,这意味着您正在GUI 线程之外创建QPixmap。

    将连接类型更改为Qt.QueuedConnection 可以解决问题吗?

    【讨论】:

    • 是的,它确实修复了它。但是现在如果我再次单击该按钮,它就会关闭。
    • 我想这是另一个需要解决的问题 :) 非常感谢您的帮助。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2013-07-12
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多