Today in class, I made a stopwatch.



This is the code that shows the Layout of the stopwatch. The time is vertical and centered. The start, stop, and reset buttons are horizontal.
def initUI(self):
self.setWindowTitle("Stopwatch")
vbox = QVBoxLayout()
vbox.addWidget(self.time_label)
self.setLayout(vbox)
self.time_label.setAlignment(Qt.AlignCenter)
hbox = QHBoxLayout()
hbox.addWidget(self.start_button)
hbox.addWidget(self.stop_button)
hbox.addWidget(self.reset_button)
vbox.addLayout(hbox)
This is the style for the stopwatch.
self.setStyleSheet("""
QPushButton, QLabel{
padding: 20px;
font-weight: bold;
font-family: calibri;
}
QPushButton{
font-size: 50px;
}
QLabel{
font-size: 120px;
background-color: hsl(200, 100%, 85%);
border-radius: 20px;
}
""")
This the code that starts the time, stops it, resets it, and updates it, and the format.
def start(self):
self.timer.start(10)
def stop(self):
self.timer.stop()
def reset(self):
self.timer.stop()
self.time = QTime(0, 0, 0, 0)
self.time_label.setText(self.format_time(self.time))
def format_time(self, time):
hours = time.hour()
minutes = time.minute()
seconds = time.second()
milliseconds = time.msec() // 10
return f"{hours:02}:{minutes:02}:{seconds:02}.{milliseconds:02}"
def update_display(self):
self.time = self.time.addMSecs(10)
self.time_label.setText(self.format_time(self.time))
No Responses