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__(不使用计时器)创建线程,但它也不起作用。

4

1 回答 1

7

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

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

请参阅有关Threads 和 QObjects的 Qt 文档。

于 2012-11-16T18:41:51.143 回答