Custom widget

To start with, we define the AnalogClock class that is inherited from QWidget. We define two variables that will be used to draw the hourHand and minuteHand of the analog clock. We also define the colors for the pointers:

class AnalogClock(QWidget):
    hourHand = QPolygon([
        QPoint(7, 8),
        QPoint(-7, 8),
        QPoint(0, -40)
    ])

    minuteHand = QPolygon([
        QPoint(7, 8),
        QPoint(-7, 8),
        QPoint(0, -70)
    ])

    hourColor = QColor(255, 0, 127)
    minuteColor = QColor(0, 127, 127, 255)

Next, we define an init function that will start the timer that will update the clock on the expiry of every minute. It also resizes the widget and sets a title for it:

def __init__(self, parent=None):
        QWidget.__init__(self)

        timer = QTimer(self)
        timer.timeout.connect(self.update)
        timer.start(1000)

        self.setWindowTitle("Analog Clock")
        self.resize(200, 200)

The core functionality of the analog clock is defined in the paintEvent() function, which would be called on the update function of the analog clock widget. We call the QTime.CurrentTime() function to update the current time from the system. The next set of lines will set the pen properties and draws the minute hand and hour hand polygons along with the line indications of the analog clock:

def paintEvent(self, event):
        side = min(self.width(), self.height())
        time = QTime.currentTime()

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogClock.hourColor)

        painter.save()
        painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)))
        painter.drawConvexPolygon(AnalogClock.hourHand)
        painter.restore()

        painter.setPen(AnalogClock.hourColor)

        for i in range(12):
            painter.drawLine(88, 0, 96, 0)
            painter.rotate(30.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogClock.minuteColor)

        painter.save()
        painter.rotate(6.0 * (time.minute() + time.second() / 60.0))
        painter.drawConvexPolygon(AnalogClock.minuteHand)
        painter.restore()

        painter.setPen(AnalogClock.minuteColor)

        for j in range(60):
            if (j % 5) != 0:
                painter.drawLine(92, 0, 96, 0)
            painter.rotate(6.0)

On running the preceding application, we will see an analog clock widget drawn, as given in the following screenshot:

Custom widget
..................Content has been hidden....................

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