PyQt-从另一个线程修改GUI [英] PyQt - Modify GUI from another thread

查看:97
本文介绍了PyQt-从另一个线程修改GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从另一个线程修改我的主布局.但是从来没有调用过run()函数 而且我遇到了错误:

I'm trying to modify my main layout from another thread. But the function run() is never called and i'm having the error:

QObject :: setParent:无法设置父级,新的父级位于另一个 线程

QObject::setParent: Cannot set parent, new parent is in a different thread

这是我的代码:

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中有什么类型的东西吗?

I really don't get it, why is it so difficult to access the GUI with PyQt? In C# you have Invoke. Is there anything of the kind in PyQt?

我尝试直接从MainWindow.__init__创建线程(不使用计时器),但是它也不起作用.

I tried creating the thread directly from MainWindow.__init__ (without using the timer) but it didn't work either.

推荐答案

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

In Qt you should never attempt to directly update the GUI from outside of the GUI thread.

相反,让您的线程发出信号并将其连接到插槽,这些插槽将从GUI线程内进行必要的更新.

Instead, have your threads emit signals and connect them to slots which do the necessary updating from within the GUI thread.

请参阅有关线程和QObjects 的Qt文档.

See the Qt documentation regarding Threads and QObjects.

这篇关于PyQt-从另一个线程修改GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆