Issue
I am trying to change a label on a button click and then after 3 seconds I want it to change back to nothing ("")
my code is this:
def apply_click(self):
ui.label_ischanged.setText("Applied!")
and I connected it to my button then I used time.sleep(3)
but I know that it stops the program not in the real time and my button stays pushed for 3 seconds and I got not responding for 3 seconds
Solution
It sound like a perfect use case for a QTimer object. The timer will run inside the QT event loop and there is no need to have any additional threads involved.
from PySide6.QtWidgets import QMainWindow, QApplication, QLabel, QVBoxLayout, QWidget, QPushButton, QMenuBar, QStatusBar
from PySide6.QtCore import QTimer
class Interface(QMainWindow):
def __init__(self):
super().__init__()
self.__build_ui()
self.timer = QTimer()
self.timer.setSingleShot(True)
self.timer.setInterval(3000)
self.timer.timeout.connect(self.timer_finished)
self.pushButton.clicked.connect(self.apply_click)
self.show()
def apply_click(self):
if not self.timer.isActive():
self.label.setText('Timer has been started. Please wait...')
self.timer.start()
def timer_finished(self):
self.label.setText('Time is over')
def __build_ui(self):
self.centralwidget = QWidget(self)
self.centralwidget.setObjectName(u"centralwidget")
self.verticalLayout = QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(u"verticalLayout")
self.label = QLabel(self.centralwidget)
self.label.setText('Start Timer')
self.label.setObjectName(u"label")
self.verticalLayout.addWidget(self.label)
self.pushButton = QPushButton(self.centralwidget)
self.pushButton.setObjectName(u"pushButton")
self.pushButton.setText('Start Timer')
self.verticalLayout.addWidget(self.pushButton)
self.setCentralWidget(self.centralwidget)
self.resize(290, 147)
if __name__ == '__main__':
app = QApplication([])
interface = Interface()
app.exec()
Answered By - Georg Stricker
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.