当我尝试从线程中使用一个 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 ,如果您还没有(如果您有,可能想发布有关您不理解的部分的问题,那里有大量重要信息)。
关于python - 无法发送另一个线程中对象的已发布事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21508401/