allin0n3 allin0n3 - 2 months ago 21
C++ Question

Creating a simple Clock in QT

I want to create a simple clock in my Qt program: QLabel which is updated once a second.

QLabel name: label_clock

My clock "script":

while (true)
{
QString time1 = QTime::currentTime().toString();
ui->label_clock->setText(time1);
}


But when I pase it into my program, you already know that it will stop executing it at this script - while will always give true, so rest of code under script will never execute -> program crashes.

What should I do to make this script work? I wanna create a simple clock which is being updated once a second.

Answer

You can use QTimer for this. Try something like this:

QTimer *t = new QTimer(this);
t->setInterval(1000);
connect(t, &QTimer::timeout, [&]() {
   QString time1 = QTime::currentTime().toString();
   ui->label_clock->setText(time1);
} );
t->start();

Of course you should enable c++11 support (add to your pro file CONFIG += c++11).