[英]QThread: Destroyed while thread is still running
我在 python 中遇到 QThreads 問題。 我想更改 label 的背景顏色。 但是我的應用程序在啟動時崩潰了。 “QThread:在線程仍在運行時被銷毀”
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
statusTh = statusThread(self)
self.connect(statusTh, SIGNAL('setStatus'), self.st, Qt.QueuedConnection)
statusTh.start()
def st(self):
if self.status == 'ON':
self.ui.label.setStyleSheet('background-color:green')
else:
self.ui.label.setStyleSheet('background-color:red')
class statusThread(QThread):
def __init__(self, mw):
super(statusThread, self).__init__()
def run(self):
while True:
time.sleep(1)
self.emit(SIGNAL('setStatus'))
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
你沒有在創建線程后存儲對線程的引用,這意味着在程序離開MainWindow
的__init__
之后的某個時間它將被垃圾收集(即銷毀)。 只要線程正在運行,您至少需要存儲它,例如使用self.statusTh
:
self.statusTh = statusThread(self)
self.connect(self.statusTh, SIGNAL('setStatus'), self.st, Qt.QueuedConnection)
self.statusTh.start()
我知道這是相當的 necroposting 但這可能很有用。 在腳本的主要部分中,需要將第一級自定義小部件存儲在變量中,而不僅僅是創建。 例如,我有一個名為 MainWindow 的自定義小部件 class,它創建了一個 QThread。 我的主要是這樣的:
from myPackage import MainWindow
if __name__ == "__main__":
app = QApplication([])
widget=MainWindow()
sys.exit(app.exec())
如果我避免使用widged =定義並且只調用 MainWindow(),我的腳本將與QThread 崩潰:線程仍在運行時已銷毀
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.