2012-11-16 277 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文檔。