我想在我的 Qt 程序中创建一个简单的时钟:QLabel,每秒更新一次。
Q标签名称:label_clock
我的时钟“脚本”:
while (true)
{
QString time1 = QTime::currentTime().toString();
ui->label_clock->setText(time1);
}
Run Code Online (Sandbox Code Playgroud)
但是当我将它粘贴到我的程序中时,您已经知道它将在该脚本处停止执行 - 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();
Run Code Online (Sandbox Code Playgroud)
当然,您应该启用 c++11 支持(添加到您的pro文件中CONFIG += c++11)。