从另一个线程修改GUI

2024-06-17 08:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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__创建线程(不使用计时器),但它也不起作用。在


Tags: runselfinitdef线程threadclassparent
1条回答
网友
1楼 · 发布于 2024-06-17 08:17:30

在Qt中,永远不要试图从GUI线程外部直接更新GUI。在

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

请参阅有关Threads and QObjects的Qt文档。在

相关问题 更多 >