【发布时间】:2021-01-18 10:41:49
【问题描述】:
创建一个 QMainWindow >> 按下开始按钮 >> 连接一个长时间运行的函数和一个 QLabel 作为 arg >> 在运行长函数时更新标签。
我想在 GUI 中更新长时间运行的函数的状态。但是一旦长时间运行的函数启动,整个窗口就会冻结
import sys
import time
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QApplication,
QLabel,
QMainWindow,
QPushButton,
QVBoxLayout,
QWidget,
)
def runLongTask(label):
label.setText('<1> sleeping for 10s ...')
time.sleep(10)
label.setText('<2> sleeping for 10s ...')
time.sleep(10)
label.setText('End')
class Window(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi()
def setupUi(self):
self.setWindowTitle("GUI freeze FIX")
self.resize(350, 250)
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self.label = QLabel()
self.label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
self.label.setText('No Update')
countBtn = QPushButton("Start")
countBtn.clicked.connect(lambda: runLongTask(self.label))
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(countBtn)
self.centralWidget.setLayout(layout)
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())
【问题讨论】: