Thread1 创建一个多线程 Thread 类的子类,点击启动线程后,每隔 1 秒钟,发送一个信号给主程序,主程序进行计数更新,点击停止线程后,停止计 数并更新
时间: 2024-03-01 09:53:31 浏览: 34
好的,我可以帮你解答这个问题。首先,你需要定义一个多线程的子类,重写run()方法,该方法会在启动线程后自动运行。在run()方法中,可以使用QThread.sleep()方法来让线程暂停一段时间,然后发送一个信号给主程序。
具体实现步骤如下:
1. 定义一个多线程的子类,如下所示:
```
class MyThread(QThread):
signal = QtCore.pyqtSignal(int) # 定义一个信号,用于向主程序发送计数更新的消息
def run(self):
count = 0
while True:
self.signal.emit(count) # 发送信号,通知主程序更新计数
count += 1
time.sleep(1) # 线程暂停1秒钟
```
2. 在主程序中创建该子类的实例,并连接信号和槽:
```
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.thread = MyThread() # 创建线程实例
self.thread.signal.connect(self.update_count) # 连接信号和槽
def start_thread(self):
self.thread.start() # 启动线程
def stop_thread(self):
self.thread.terminate() # 停止线程
def update_count(self, count):
# 更新计数
self.count_label.setText(str(count))
```
3. 在界面中添加开始和停止按钮,并将其与主程序中的start_thread()和stop_thread()方法连接起来。
```
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.thread = MyThread() # 创建线程实例
self.thread.signal.connect(self.update_count) # 连接信号和槽
# 创建开始和停止按钮
self.start_button = QtWidgets.QPushButton('开始', self)
self.start_button.clicked.connect(self.start_thread)
self.stop_button = QtWidgets.QPushButton('停止', self)
self.stop_button.clicked.connect(self.stop_thread)
# 创建计数标签
self.count_label = QtWidgets.QLabel('0', self)
# 设置界面布局
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.start_button)
layout.addWidget(self.stop_button)
layout.addWidget(self.count_label)
central_widget = QtWidgets.QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def start_thread(self):
self.thread.start() # 启动线程
def stop_thread(self):
self.thread.terminate() # 停止线程
def update_count(self, count):
# 更新计数
self.count_label.setText(str(count))
```
这样,当点击开始按钮后,线程会启动,并每隔1秒钟发送一个信号给主程序,主程序会更新计数标签的值。当点击停止按钮后,线程会停止,并停止更新计数。