python pyqt 判断线程是否启动
时间: 2023-11-23 11:55:08 浏览: 111
使用QThread类的isRunning()方法来判断线程是否启动。该方法返回一个布尔值,如果线程正在运行,则返回True,否则返回False。
```python
import sys
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class MyThread(QThread):
started_signal = pyqtSignal()
finished_signal = pyqtSignal()
def __init__(self):
super().__init__()
def run(self):
self.started_signal.emit()
# 线程执行的任务
self.finished_signal.emit()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('判断线程是否启动')
self.btn_start = QPushButton('启动线程', self)
self.btn_start.move(50, 50)
self.btn_start.clicked.connect(self.startThread)
self.btn_check = QPushButton('检查线程状态', self)
self.btn_check.move(150, 50)
self.btn_check.clicked.connect(self.checkThread)
self.thread = MyThread()
self.thread.started_signal.connect(self.onStarted)
self.thread.finished_signal.connect(self.onFinished)
def startThread(self):
self.thread.start()
def checkThread(self):
if self.thread.isRunning():
print('线程正在运行')
else:
print('线程未启动或已结束')
def onStarted(self):
print('线程已启动')
def onFinished(self):
print('线程已结束')
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
```
阅读全文