Coders Packet

Digital Clock in C++ using Qt Framework


I've made a Digital Clock in C++ using Qt Framework. It'll show the current time of your time zone.


                                                                   Creating a Digital Clock


A clock is an instrument to keep the measurement of time. It is one of the oldest human inventions.

Steps to create a Digital Clock in C++ using Qt:

Step 1: Install Qt on your computer.

Step 2: Create a Qt Widget Application.

Step 3: Then go to the digitalclock.ui and give a relevant background colour so that it looks nice. Then add a label and adjust it horizontally.

Step 4: After that, add all the necessary header files. You can use your own header files also, but for the sake of simplicity I'm using the predefined header files in Qt. Those are:

#include "QDebug"

#include "QDateTime"

#include "QString"

Step 6: Add the QTimer header file in digitalclock.h header-file. And add this code there:

public slots:
    void func();

    Ui::DigitalClock *ui;
    QTimer *timer;

Here we've created a QTimer object.

Step 7: Then add this code in digitalclock.cpp file under the first block of code:

timer = new QTimer();

The 3rd line of code is connecting the timer object to the slot. And timer->start(1000) updates the time after 1000ms i.e, 1s. We can use there 5000 as well but in that case, the time will be updated after 5s.

Step 7: Now let's do the last thing, let's create the func() function.

void DigitalClock::func()
    QTime time = QTime::currentTime();
    QString time_text=time.toString("hh:mm:ss");

Here the time holds the current time. The toString function converts the current time to string and the time_text object holds it. Here "hh:mm::ss" denotes that it'll display only two digits. And the last line displays the current time to the label. We can change the colour of the text displayed.

Step 8: Now Build and Run the code.

Download Complete Code


No comments yet