PyQt - Modify GUI from another thread

匿名 (未验证) 提交于 2019-12-03 01:04:01

问题:

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.

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!