Ser*_*tin 16 python pyqt qthread
我在python中遇到QThreads的问题.我想改变标签的背景颜色.但我的应用程序在启动时崩溃."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_())
Run Code Online (Sandbox Code Playgroud)
rai*_*ner 30
你没有在创建线程后存储对线程的引用,这意味着在程序离开MainWindows 之后的某个时间它将被垃圾收集(即销毁)__init__.只要线程正在运行,您至少需要存储它,例如使用self.statusTh:
self.statusTh = statusThread(self)
self.connect(self.statusTh, SIGNAL('setStatus'), self.st, Qt.QueuedConnection)
self.statusTh.start()
Run Code Online (Sandbox Code Playgroud)