我是 Qt C++ 的新手,从我在网上找到的少数资源中,我无法仅提取我需要向表单添加倒数计时器的部分。我没有尝试添加任何按钮或其他功能。只需要有一个从 1:00 开始的计时器,然后减少直到 0:00 到达,此时我需要显示某种消息,指示用户时间到了。我想也许添加一个标签来显示计时器是一种简单的方法(但现在确定我在这方面是否正确)。
到目前为止,我创建了一个新的 Qt 应用程序项目,向我的主窗体添加了一个标签,并从我在 http://doc.qt.io/archives/qt-4.8/timers.html 获得的内容中向 mainwindow.cpp 添加了一些计时器代码。 :
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//Initialize "countdown" label text
ui->countdown->setText("1:00");
//Connect timer to slot so it gets updated
timer = new QTimer();
connect(timer, SIGNAL(timeout()), this, SLOT(updateCountdown()));
//It is started with a value of 1000 milliseconds, indicating that it will time out every second.
timer->start(1000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::updateCountdown()
{
//do something along the lines of ui->countdown->setText(....);
}
在 mainwindow.h 中,我添加了一个 QTimer *timer;
作为公共(public)属性,还添加了 void updateCountdown();
作为私有(private)槽。
但我不确定如何从这里继续下去。我认为下一步是每秒减少计时器并在“倒计时”标签上显示(这将在 updateCountdown 插槽上完成)但我不知道如何做。 我也不确定如何在倒计时到达 0:00 时触发消息(可能在 QFrame 上)。
最佳答案
来自 QTimer documentation ,函数 updateCountdown()
在您的配置中每 1 秒调用一次。因此,每次调用此函数并在 UI 中更新时,您都应该从计时器中减少一秒。目前您没有将时间存储在任何地方,所以我建议您将其添加为全局暂时,例如QTime time(0, 1, 0)
QTime Documentation .
然后在 updateCountdown()
中,调用 time.addSecs(-1);
然后 ui->countdown->setText(time.toString("m:ss"));
。然后很容易检查它是否为“0:00”并执行其他操作。
希望对你有帮助
关于c++ - Qt C++ : how to add a simple countdown timer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53459173/