# cPy qt_intro : timer
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-01-26  initial release

import  os;                 os.system('clear')
from    PySide6.QtWidgets   import  QApplication, QWidget, QLabel, QPushButton
from    PySide6.QtCore      import  QTimer

# ========================== demo 1 ==============================

# most simple QTimer application. Print '*' @ 1 Sec
class Gui1(QWidget):

    def __init__(self):
        app = QApplication()                            # Qt framework
        super().__init__()                              # instantiate QWidget = GUI
        tmr = QTimer()
        tmr.timeout.connect(self.onTimer)
        tmr.start(1000)                                 # timer interval is 1 Sec
        self.show()
        app.exec()


    def onTimer(self):
        print('*', end='', flush=True)


Gui1()

# ========================== demo 2 ==============================

# stopwatch with 10 mSec resolution
class Gui2(QWidget):

    def __init__(self):
        app = QApplication()                            # Qt framework
        super().__init__()                              # instantiate QWidget = GUI
        self.lbl = QLabel('00:00.00', self)
        self.lbl.move(50, 10)
        self.lbl.setStyleSheet('font-size: 40px; font-weight: bold; color: red')
        btn = QPushButton('Start', self)
        btn.setGeometry(40, 70, 70, 30)
        btn.clicked.connect(self.onBtnStart)
        btn = QPushButton('Stop', self)
        btn.setGeometry(150, 70, 70, 30)
        btn.clicked.connect(self.onBtnStop)
        self.ticks = None
        tmr = QTimer(self)
        tmr.timeout.connect(self.onTimer)
        tmr.start(10)                                 # timer interval is 10 mSec
        self.show()
        app.exec()


    # show ticks as MM:SS:mSec
    def showTime(self):
        if isinstance(self.ticks, int):
            t, msec   = divmod(self.ticks, 100)
            min, sec  = divmod(t, 60)
            self.lbl.setText(f'{min:02}:{sec:02}.{msec:02}')


    # start counting
    def onBtnStart(self, sts):
        self.ticks = 0
        self.showTime()


    # stop counting and show ticks
    def onBtnStop(self, sts):
        self.showTime()
        self.ticks = None


    # called @ 10 mSec, inc ticks and show ticks @ 100 mSec
    def onTimer(self):
        if isinstance(self.ticks, int):
            self.ticks += 1
            if self.ticks % 10 == 0:
                self.showTime()


#Gui2()

# ============================== end =============================
