0

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.

allin0n3
  • 157
  • 1
  • 4
  • 13

1 Answers1

5

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).

Evgeny
  • 3,910
  • 2
  • 20
  • 37