When I tried to use QElapsedTimer to clear a text in a label I couldn't find a way of using it without a QTimer. Is there a way of connecting a method so that it will do something when the QElapsedTimer reaches a certain value? To be more specific, I want to clear the text I set to lblSendError
using the print_username()
method after 5 seconds ahve passed. Here I have used the clear_username()
method to clear it. Right now I have connected it to a QTimer so that it would run periodically.
This is my current implementation of QElapsedTimer in my code:
class win2(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
uic.loadUi('designs/win2.ui', self)
self.butPrevious.clicked.connect(self.goto_page1)
self.butSend.clicked.connect(self.print_username)
self.clearTimerE = QtCore.QElapsedTimer()
print(dir(self.clearTimerE))
self.clearTimer = QtCore.QTimer()
self.clearTimer.setInterval(1000)
self.clearTimer.timeout.connect(self.clear_username)
def goto_page1(self):
self.hide()
w1.show()
def print_username(self):
self.lblSendError.setText(w1.textUsername.toPlainText())
self.clearTimerE.start()
self.clearTimer.start()
def clear_username(self):
print(self.clearTimerE.elapsed())
if self.clearTimerE.elapsed() >= 4000:
self.lblSendError.setText('')
#self.clearTimerE.restart()
self.clearTimer.stop()
You only need a single-shot timer for this - an elapsed timer isn't needed. Also, I would advise putting all the code for this in your main-window class, as this will make it much easier to access the instances of the other two classes.
Here is a solution based on the code from your previous question:
class MainApp(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('designs/win_stacked.ui', self)
self.win_1 = win1()
self.win_2 = win2()
self.stackedWidget.addWidget(self.win_1)
self.stackedWidget.addWidget(self.win_2)
self.stackedWidget.setCurrentWidget(self.win_2)
self.win_2.butPrevious.clicked.connect(self.goto_page1)
self.win_2.butSend.clicked.connect(self.print_username)
self.clearTimer = QtCore.QTimer()
self.clearTimer.setSingleShot(True)
self.clearTimer.setInterval(5000)
self.clearTimer.timeout.connect(self.clear_username)
def goto_page1(self):
self.stackedWidget.setCurrentWidget(self.win_1)
def print_username(self):
self.win_2.lblSendError.setText(self.win_1.textUsername.toPlainText())
self.clearTimer.start()
def clear_username(self):
self.win_2.lblSendError.setText('')