[英]PyQt - Modify GUI from another thread
我正在嘗試從另一個線程修改我的主要布局。 但是函數 run() 從來沒有被調用過,我遇到了錯誤:
QObject::setParent:無法設置父級,新父級在不同的線程中
這是我的代碼:
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# 中,您有 Invoke。 PyQt 中有這樣的東西嗎?
我嘗試直接從MainWindow.__init__
(不使用計時器)創建線程,但它也不起作用。
在 Qt 中,您永遠不應該嘗試從 GUI 線程外部直接更新 GUI。
相反,讓您的線程發出信號並將它們連接到從 GUI 線程內進行必要更新的插槽。
請參閱有關Threads 和 QObjects的 Qt 文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.