这个问题在这里已有答案:
我试图在同一个函数中执行多个动作。在下面的代码中,您将看到一个带有按钮和标签的窗口页面。我希望看到“蓝色”,睡眠2秒后我想在我的标签上看到“红色”文字。但是当我点击按钮时,所有功能都像块一样工作,经过两秒钟后,标签文本变为“红色”。是的,首先它变为蓝色,但我看不到,因为它太快了。我该如何解决这个问题?
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
#label is Hello now
self.label=QLabel("Hello")
self.button = QPushButton("Change it")
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
self.button.clicked.connect(self.func)
def func(self):
self.label.setText("BLUE")
time.sleep(2)
self.label.setText("RED")
void QTimer :: singleShot(int msec,const QObject * receiver,const char * member)
此静态函数在给定时间间隔后调用一个槽。
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
#label is Hello now
self.label = QLabel("Hello")
self.button = QPushButton("Change it")
self.button.clicked.connect(self.func)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
def func(self):
self.label.setText("BLUE")
# QApplication.processEvents()
# QThread.msleep(2000)
# self.label.setText("RED")
QTimer.singleShot(2000, lambda : self.label.setText("RED")) # <----
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = Form()
w.show()
sys.exit(app.exec_())