简体   繁体   English

PyQt - 从另一个线程修改 GUI

[英]PyQt - Modify GUI from another thread

I'm trying to modify my main layout from another thread.我正在尝试从另一个线程修改我的主要布局。 But the function run() is never called and i'm having the error:但是函数 run() 从来没有被调用过,我遇到了错误:

QObject::setParent: Cannot set parent, new parent is in a different thread QObject::setParent:无法设置父级,新父级在不同的线程中

Here's my code:这是我的代码:

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_())

I really don't get it, why is it so difficult to access the GUI with PyQt?真不明白,为什么用PyQt访问GUI这么难? In C# you have Invoke.在 C# 中,您有 Invoke。 Is there anything of the kind in PyQt? PyQt 中有这样的东西吗?

I tried creating the thread directly from MainWindow.__init__ (without using the timer) but it didn't work either.我尝试直接从MainWindow.__init__ (不使用计时器)创建线程,但它也不起作用。

In Qt you should never attempt to directly update the GUI from outside of the GUI thread.在 Qt 中,您永远不应该尝试从 GUI 线程外部直接更新 GUI。

Instead, have your threads emit signals and connect them to slots which do the necessary updating from within the GUI thread.相反,让您的线程发出信号并将它们连接到从 GUI 线程内进行必要更新的插槽。

See the Qt documentation regarding Threads and QObjects .请参阅有关Threads 和 QObjects的 Qt 文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM