For a short month, here’s a short widget: a self updating time label
No, it doesn’t actually look like the picture above, that’s from this post. It actually looks like this:
It’s not that exciting, but it starts its own timer so you don’t have to do anything – just shove it somewhere within your program and it handles the rest; updating itself so it always shows the current time.
from PySide6.QtWidgets import QApplication, QLabel
from PySide6.QtCore import QDateTime, QTimer, Qt
import sys, os
class timeLabel(QLabel):
"self-updating label showing current time, from Orthallelous"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setAlignment(Qt.AlignCenter)
self.timer = QTimer(self)
self.timer.setInterval(100)
self.timer.timeout.connect(self.updateTime)
self.use24hr = False
self.timer.start()
return
def updateTime(self):
"update self with current time"
dt = QDateTime.currentDateTime()
toStr = dt.toString
# string parts
yr = toStr('yyyy')
d1 = toStr('ddd MMM d')
hm = toStr('h:mm:ss A')
d2 = toStr('dddd, MMMM d')
if self.use24hr: hm = toStr('HH:mm:ss')
else: hm = toStr('h:mm:ss A')
# suffixes
dy = dt.date().day()
th = {0: 'th', 1: 'st', 2: 'nd', 3: 'rd'}
sf = th[0] if 9 < dy%100 < 14 else th.get(dy%10, th[0])
#sx = f'<span style="vertical-align:super;">{sf}</span>'
sx = f'<sup>{sf}</sup>'
# set label
#self.setText(f'{d1}{sf} {yr}, {hm}')
self.setText(f'{d1}{sx} {yr}, {hm}')
self.setToolTip(f'{d2}{sf}, {yr}')
return
def showMessage(self, txt, msec=2500):
"pause the clock and show a message for msecs"
self.timer.stop()
self.setText(txt)
self.setToolTip(txt)
QTimer.singleShot(msec, self.timer.start)
return
def set24Hour(self, state):
"set the clock to use 24 hour mode or not"
self.use24hr = bool(state)
def start(self):
"start the clock"
self.timer.start()
def stop(self):
"stop the clock"
self.timer.stop()
self.setToolTip('')
self.setText('Clock Disabled')
if __name__ == '__main__':
app = QApplication(sys.argv)
win = timeLabel()
win.show()
app.exec()
It has a few options, it can show a message for a short period of time before switching back to the clock, and whether or not you want it to display the time in 24 hour format or not.
And if you want to track other time-related things, I’ve already got a program for that!


Leave a comment