Apr-17-2020, 06:39 PM
(This post was last modified: Apr-17-2020, 06:39 PM by deanhystad.)
def __init__(self, *args, **kwargs): self.timer = QTimer() self.timer.timeout.connect(self.update_time) … self.start_button = QPushButton(self) self.start_button.setStyleSheet("QPushButton {background-color: yellow; font-size: 15pt;}") self.start_button.setText("Start") self.start_button.clicked.connect(self.start_timer) # Connect button here. Right after you make it self.my_counter = 0 self.my_counter1 = 0 self.my_counter2 = 0I have PySide2 instead of Qt5, but they are nearly identical. The signal for the QPushbutton is clicked() instead of click(). Decided to use only one label for the time display 'cause I am lazy.
import sys from PySide2.QtCore import QTimer from PySide2.QtWidgets import QWidget, QLabel, QPushButton, QGridLayout, QApplication class Stopwatch(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.tics = 0 self.increment = 10 self.timer = QTimer() self.timer.timeout.connect(self.update_time) self.time_display = QLabel(self, text='00:00:00.00') self.time_display.setStyleSheet("QLabel {background-color: white; font-size: 50pt;}") self.start_button = QPushButton(self) self.start_button.setStyleSheet("QPushButton {background-color: yellow; font-size: 20pt;}") self.start_button.setText("Start") self.start_button.clicked.connect(self.start_timer) self.layout = QGridLayout(self) self.layout.addWidget(self.time_display, 0, 0) self.layout.addWidget(self.start_button, 1, 0) def update_time(self): """Increment counter and update time display""" # Calculate hours:minutes:seconds self.tics += self.increment h = self.tics // 3600000 m = (self.tics // 60000) % 60 s = (self.tics / 1000) % 60 self.time_display.setText(f'{h:02d}:{m:02d}:{s:05.2f}') def start_timer(self): """Start/Stop the timer""" if self.start_button.text() == 'Start': self.tics = 0 self.start_button.setText('Stop') self.timer.start(self.increment) else: self.timer.stop() self.start_button.setText('Start') app = QApplication(sys.argv) win = Stopwatch() win.setWindowTitle('Stopwatch') win.show() sys.exit(app.exec_())