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

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

问题描述

我正在尝试从另一个线程修改我的主要布局.但是函数 run() 永远不会被调用我遇到了错误:

<块引用>

QObject::setParent: 不能设置父级,新的父级在不同的线程

这是我的代码:

class FeedRetrievingThread(QtCore.QThread):def __init__(self, parent=None):super(FeedRetrievingThread, self).__init__(parent)self.mainLayout = parent.mainLayout定义运行(自我):# 用 self.mainLayout 做事类 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):如果不是 self.feedRetrievingThread.isRunning():打印正在运行的线程".self.feedRetrievingThread.start()如果 __name__ == '__main__':app = QtGui.QApplication(sys.argv)主窗口 = 主窗口()mainWindow.show()sys.exit(app.exec_())

真不明白,为什么用PyQt访问GUI这么难?在 C# 中,您有 Invoke.PyQt 中有这样的东西吗?

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

解决方案

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

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

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

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: Cannot set parent, new parent is in a different thread

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? In C# you have Invoke. Is there anything of the kind in PyQt?

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

解决方案

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

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

See the Qt documentation regarding Threads and QObjects.

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

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