【发布时间】:2014-02-25 19:40:53
【问题描述】:
当我尝试使用线程中的一个 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 回答中所写,如果我做对了,我不能这样做。但是那我该怎么做呢?
【问题讨论】:
-
实际上 Qt 小部件不是线程安全的。
-
@fasked,没有解决方法吗?
-
没有合法的解决方法。 Qt 文档明确表示只能从主线程访问小部件。
-
@DmitryMikhaylov 如果有帮助的话,我创建了一个不错的实用程序,它允许您在 Qt 应用程序的主线程中运行任意方法。因此,从一个线程中,您可以调用
inmain(widget.setText,my_text)例如,然后它将一个事件发布到 MainThread 并运行您指定的方法。如果您有兴趣,请查看bitbucket.org/philipstarkey/qtutils。为 PySide 编写,但对您来说移植到 PyQt 应该很简单! -
谢谢@three_pineapples,我会试一试的。