出错原因在于线程还在运行的时候线程对象就已经被摧毁了,很可能是被垃圾回收了。
You're not storing a reference to the thread after it's been created, which means that it will be garbage collected (ie. destroyed) some time after the program leaves MainWindows init. You need to store it at least as long as the thread is running, for example use self.statusTh:
self.statusTh = statusThread(self)
self.connect(self.statusTh, SIGNAL('setStatus'), self.st, Qt.QueuedConnection)
self.statusTh.start()
import sys
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
import time
class MainWindow(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.initUi()
self.conn()
self.show()
# init self
def initUi(self):
self.setWindowTitle('QThread example')
self.resize(300, 200)
layout = QVBoxLayout()
self.label = QLabel('labeltext')
self.btn = QPushButton('OK')
self.btn_close =QPushButton('EXIT')
# self.setCentralWidget(self.label)
layout.addWidget(self.label, 0, Qt.AlignCenter)
layout.addWidget(self.btn)
layout.addWidget(self.btn_close)
self.setLayout(layout)
self.thread = Worker()
def conn(self):
self.thread.sig.connect(self.updateLabel)
self.btn.clicked.connect(self.buttonClicked)
self.btn_close.clicked.connect(self.btn_close_clicked)
@Slot()
def buttonClicked(self):
self.thread.start()
@Slot()
def updateLabel(self, text):
self.label.setText(text)
@Slot()
def btn_close_clicked(self):
self.thread.__del__()
self.close()
class Worker(QThread):
sig = Signal(str)
def __init__(self, parent=None):
print('Created a new thread of Worker')
super(Worker, self).__init__(parent)
self.status = True
self.count = 0
def __del__(self):
print('Stop thread task running.')
self.status = False
self.wait()
def run(self):
print('Start a new thread task.')
while self.status:
self.count += 1
self.s = f"已执行{self.count}秒"
self.sig.emit(self.s)
time.sleep(1)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
app.exec()