Tracking time using timers

Most of the GUI applications are time bound, and it is extremely important to use timers to capture information about the program runtime and other similar tasks. You may also use timers to generate some event at specified time intervals, calculate the elapsed time for some action, implement a countdown timer, and so on. This section of the chapter covers how to create and use timers in our application, and we will develop a digital clock application explaining the concept of timers.

The classes that are used to create this application in Qt are PySide.QtCore.QTimer and PySide.QtCore.QDateTime. The QTimer class provides a high-level programming interface for timers. It provides repetitive and single-shot timers. Repetitive timers run continuously and restart at the expiry of one time slot. Single-shot timers will run exactly once and expire after one time slot. A timeout event will occur at the expiry of the given time slot. The timer can be started by issuing a start call to the QTimer object and can be stopped anywhere in between before the expiry of the time slot by issuing a stop signal:

        QTimer.start(1000)
        QTimer.stop()

The unit of the timer is in milliseconds. The accuracy of timers depends on the underlying operating system and hardware. Most platforms support a resolution of 1 millisecond, though the accuracy of the timer will not match this, and it is not guaranteed.

The PySide.QtCore.QDateTime class provides a calendar date and clock time function. It is a combination of the PySide.QtCore.QDate and PySide.QtCore.QTime classes. As with any other framework, the QDateTime class provides functions to compare datetimes and for manipulation of a datetime. It provides a full set operator to compare two QDateTime objects, where a smaller object means that it occurred earlier and a larger object means that it occurred later. The QDateTime can store datetimes both as local and as UTC. The QDateTime.toUTC() function can be applied on a QDateTime object to convert the local time to UTC. This class handles and is aware of daylight saving time:

# Import required modules
import sys
from PySide.QtCore import QDateTime, QTimer, SIGNAL
from PySide.QtGui import QApplication, QWidget, QLCDNumber,QDesktopWidget

class MyTimer(QWidget):
    """ Our Main Window class for Timer
    """
    def __init__(self):
        """ Constructor Function
        """
        super(MyTimer,self).__init__()
        self.initGUI()

    def initGUI(self):
        self.setWindowTitle('My Digital Clock')
        timer = QTimer(self)
        self.connect(timer, SIGNAL("timeout()"), self.updtTime)
        self.myTimeDisplay = QLCDNumber(self)
        self.myTimeDisplay.setSegmentStyle(QLCDNumber.Filled)
        self.myTimeDisplay.setDigitCount(8)
        self.myTimeDisplay.resize(500, 150)
        self.updtTime() # To Display the current time before call by timer event. Otherwise it will start with 0
        self.center()
        timer.start(1000)
        self.show()

    def center(self):
        """
            Function to center the application    
        """
        qRect = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qRect.moveCenter(centerPoint)
        self.move(qRect.topLeft())

    def updtTime(self):
        """ Function to update current time
        """
        currentTime = QDateTime.currentDateTime().toString('hh:mm:ss')
        self.myTimeDisplay.display(currentTime)

# Main Function       
if __name__ == '__main__':
    # Exception Handling
    try:        
        myApp = QApplication(sys.argv)
        myWindow = MyTimer()
        myApp.exec_()
        sys.exit(0)
    except NameError:
        print("Name Error:", sys.exc_info()[1])
    except SystemExit:
        print("Closing Window...")
    except Exception:
        print(sys.exc_info()[1])

The preceding program will display a digital clock on execution. To display the time with the precision in seconds, we start a timer that times out every second. On timeout of the timer, we call the updtTime() function, which will update the current time and display it on the screen. In order to display the time in the digital format, we used a special display in this program, which is different from the previous ones. The PySide.QtGui.QLCDNumber will display a number with LCD-like digits, which gives the appearance of a digital clock. The digits/numbers that can be shown with LCDNumber are 0/O, 1, 2, 3, 4, 5/S, 6, 7, 8, 9/g, minus, decimal point, A, B, C, D, E, F, h, H, L, o, P, r, u, U, Y, colon, degree sign (which is specified as a single quote in the string) and space. PySide.QtGui.QLCDNumber substitutes spaces for illegal characters. Using this, we can just output the text/number in any size. The setSegmentStyle() function sets the style of the QLCDNumber that has to be displayed. It could take the following values, as displayed in the table:

Tracking time using timers

Constant

Description

QLCDNumber.Outline

This gives us raised segments that are filled with the background color

QLCDNumber.Filled

This gives us raised segments that are filled with the windowText color

QLCDNumber.Flat

This gives us flat segments that are filled with the windowText color

One more thing to note here is that the setDigitCount function will set the number of digits to show on the display, which defaults to five.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.22.179