2012-11-16 278 views
3

我想从另一个线程修改我的主要布局。但功能的run()不会被调用 ,我有错误:PyQt - 从另一个线程修改GUI

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#中你有调用。在PyQt中有这种类型的东西吗?

我试图直接从MainWindow.__init__(不使用计时器)创建线程,但它也没有工作。

回答

6

在Qt中你不应该直接尝试从GUI线程外部更新GUI。

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

查看关于Threads and QObjects的Qt文档。