# Introduction to Qt - demonstrating task QTimer controlled. main = ex13_main_qtimer.py
# by Anthony Vogelaar, Perth Scotland
# rev 0.10  2024-04-02  Initial release

from    PySide6.QtWidgets   import  QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton
from    PySide6.QtCore      import  Qt, QTimer

# ================================== GUI =========================================

class GUI(QWidget):

    # initialise GUI background
    def __init__(self, owner):
        self.owner = owner
        self.app   = QApplication([])
        super().__init__()
        self.setWindowTitle('The Title')

        lo_main = QVBoxLayout()
        self.label = QLabel('label', self)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet("font-size: 20px; font-weight: bold; color: red")
        lo_main.addWidget(self.label)

        lo_buttons = QHBoxLayout()
        for caption in('Date', 'Hour', 'Minute', 'Second', 'Counter'):
            btn = QPushButton(caption)
            btn.clicked.connect(self.onBtnClick)
            lo_buttons.addWidget(btn)

        lo_main.addLayout(lo_buttons)
        self.setLayout(lo_main)

        self.timer = QTimer()
        self.timer.timeout.connect(self.onTimer)
        self.timer.start(100)                            # Call onTimer @ 100 mSec
        self.show()


    # handle buttons onClick signals, send dictionary to controller
    def onBtnClick(self):
        self.owner.doCommand(dict(btn_click=self.sender().text()))


    # handle 10 Hz timer signal, send dictionary to controller
    def onTimer(self):
        self.owner.doCommand(dict(timer=100))


    # handle incoming commands (from controller)
    def doCommand(self, d):
        for k, v in d.items():
            if k == 'msg': self.label.setText(v)

# ================================= Test =====================================
    
if __name__ == '__main__':

    import  os, sys;            os.system('clear')
    from    PySide6.QtWidgets   import  QApplication

    class Controller:

        def __init__(self):
            gui = GUI(self)
            sys.exit(gui.app.exec())


        def doCommand(self, d):
            print(d)


    Controller()

# ================================= End ==========================================
