在 QT 中创建一个简单的时钟

Creating a simple Clock in QT

我想在我的 Qt 程序中创建一个简单的时钟:每秒更新一次的 QLabel。

Q标签名称:label_clock

我的时钟"script":

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

但是当我将它放入我的程序中时,您已经知道它会在此脚本中停止执行 - while 始终给出 true,因此脚本下的其余代码将永远不会执行 -> 程序崩溃。

我应该怎么做才能使这个脚本起作用?我想创建一个每秒更新一次的简单时钟。

您可以为此使用 QTimer。尝试这样的事情:

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

当然你应该启用 c++11 支持(添加到你的 pro 文件 CONFIG += c++11)。