[英]PyQt - Modify GUI from another thread
我正在尝试从另一个线程修改我的主要布局。 但是函数 run() 从来没有被调用过,我遇到了错误:
QObject::setParent:无法设置父级,新父级在不同的线程中
这是我的代码:
class FeedRetrievingThread(QtCore.QThread):
def __init__(self, parent=None):
super(FeedRetrievingThread, self).__init__(parent)
self.mainLayout = parent.mainLayout
def run(self):
# Do things with self.mainLayout
class MainWindow(QtGui.QDialog):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.mainLayout = QtGui.QGridLayout()
self.setLayout(self.mainLayout)
self.feedRetrievingThread = FeedRetrievingThread(self)
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.updateFeed)
self.timer.start(1000)
def updateFeed(self):
if not self.feedRetrievingThread.isRunning():
print 'Running thread.'
self.feedRetrievingThread.start()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
真不明白,为什么用PyQt访问GUI这么难? 在 C# 中,您有 Invoke。 PyQt 中有这样的东西吗?
我尝试直接从MainWindow.__init__
(不使用计时器)创建线程,但它也不起作用。
在 Qt 中,您永远不应该尝试从 GUI 线程外部直接更新 GUI。
相反,让您的线程发出信号并将它们连接到从 GUI 线程内进行必要更新的插槽。
请参阅有关Threads 和 QObjects的 Qt 文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.