Skip to main content
 首页 » 编程设计

python之无法发送另一个线程中对象的已发布事件

2024年11月01日9duanxz

当我试图从线程中使用一个 QDialog 对象时,我得到了这个错误。 这是我正在使用的代码:

import threading 
import test_qdialog 
from PyQt4 import QtGui, QtCore 
 
 
class MyThread(threading.Thread): 
    def __init__(self, id, window, mutex): 
        self.id = id 
        self.window = window 
        self.mutex = mutex 
        super(MyThread, self).__init__() 
 
    def run(self): 
        with self.mutex: 
            result = self.window.exec_() 
            if result == QtGui.QDialog.Accepted: 
                print "Thread %d: %s" % (self.id, self.window.message_input.text()) 
 
 
if __name__ == "__main__": 
    import sys 
    app = QtGui.QApplication(sys.argv) 
 
    mutex = threading.Lock() 
    threads = [] 
    window = test_qdialog.MyDialog() 
 
    for i in range(5): 
        thread = MyThread(i, window, mutex) 
        thread.start() 
        threads.append(thread) 
 
    for thread in threads: 
        thread.join() 
 
    sys.exit(app.exec_()) 

写在this回答,如果我做对了,我不能这样做。但是我该怎么做呢?

请您参考如下方法:

您只能在主线程上创建和使用 GUI 小部件(我知道的每个 UI 库都是这样)。但是,您可以使用 QtCore.QtThread 轻松地将信号从线程传递到主线程。例如参见 PyQt threads and signals - how to properly retrieve values 的答案(即使答案不是 OP 想要的,它也与您的情况相关)。也可以找this SO post有用。

因此,不是从线程创建或访问对话框,而是从线程发出信号,并让主窗口连接到它,在它接收到信号时创建对话框。 Qt 负责在线程之间传输数据。会像魅力一样工作。

一定要仔细看Qt Threading Basics ,如果你还没有(如果你有,可能想发布关于你不理解的部分的问题,那里有吨的重要信息)。