menator01
Gold Coder
Just a short example of using pyqt6 and QTimer for anyone interested. Show and hide a label. Display and close a message box.
Python:
# Do the imports
from PyQt6.QtWidgets import (QApplication, QWidget, QLabel, QPushButton, QMessageBox, QGridLayout,
QMainWindow)
from PyQt6.QtCore import QTimer
import sys
'''
The class for creating and viewing
'''
class View(QMainWindow):
def __init__(self):
super().__init__()
self.resize(300, 80)
''' Create a label and set the style. Set the min and max height '''
self.label = QLabel('Hi, I am a label')
self.label.setStyleSheet('border: 1px solid black;')
self.label.setMaximumHeight(25)
self.label.setMinimumHeight(25)
''' Same as above but this label will display the timer '''
self.label2 = QLabel()
self.label2.setStyleSheet('border: 1px solid black; background-color: lightyellow')
self.label2.setMaximumHeight(25)
self.label2.setMinimumHeight(25)
self.label2.hide()
''' Create a button '''
self.button = QPushButton('Click Me')
''' Set up the window layout '''
layout = QGridLayout()
layout.addWidget(self.label, 0, 0, 1, 1)
layout.addWidget(self.label2, 1, 0, 1, 1)
layout.addWidget(self.button, 2, 0, 1, 1)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
''' Class for controlling all actions of the window '''
class Controller:
def __init__(self, view):
self.view = view
''' Set a duration for the timer '''
self.duration = 5
''' Action to perform when the button is pressed '''
self.view.button.pressed.connect(self.show_msg)
''' Creates a popup box and show the message inthe 2nd label. Starts a timer to close both. '''
def show_msg(self):
self.view.label2.setText(f'I am going to close in {self.duration} seconds.')
self.view.label2.show()
self.timer = QTimer()
self.timer.timeout.connect(self.update)
self.timer.start(1000)
self.msg = QMessageBox()
self.msg.setText(f'I am going to close in {self.duration} seconds.')
self.msg.setIcon(QMessageBox.Icon.Information)
self.msg.exec()
''' Action to perform when the timer ends. Resets everything. Set text for label and message box'''
def update(self):
self.view.label2.setText(f'I am going to close in {self.duration} seconds.')
self.msg.setText(f'I am going to close in {self.duration - 2} seconds.')
self.duration -= 1
''' Closes the message box 2 seconds before the label '''
box_dur = self.duration - 2
if box_dur < 0:
self.msg.close()
''' Hide the label and reset counter to 5 '''
if self.duration < 0:
self.timer.stop()
self.view.label2.hide()
self.duration = 5
if __name__ == '__main__':
app = QApplication(sys.argv)
controller = Controller(View())
controller.view.show()
sys.exit(app.exec())