PyQt - 从另一个线程修改GUI

5

我正在尝试从另一个线程修改我的主布局。但函数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__创建线程(而不使用计时器),但这也不起作用。
1个回答

7

在Qt中,您不应该尝试从GUI线程之外直接更新GUI。

相反,让您的线程发出信号,并将它们连接到槽中,在GUI线程内进行必要的更新。

有关线程和QObjects的更多信息,请参见Qt文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接