Qt C ++:如何添加简单的倒数计时器?

时间:2018-11-24 14:29:35

标签: c++ qt timer

我是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;作为公共属性,还添加了void updateCountdown();作为私有位置。

但是我不确定如何从这里继续。我认为下一步是每秒减少计时器,并在“倒数”标签上显示出来(这将在 updateCountdown 插槽上完成),但我不知道如何做。 我也不确定倒数到0:00时如何触发消息(也许在QFrame上)。

1 个答案:

答案 0 :(得分:2)

QTimer documentation中,配置中每1秒钟调用一次函数updateCountdown()。因此,每次调用此函数并在UI中进行更新时,您都应将计时器减少一秒钟。当前您不在任何地方存储时间,因此建议您暂时将其添加为全局 ,例如QTime time(0, 1, 0) QTime Documentation

然后在updateCountdown()内,依次调用time.addSecs(-1);ui->countdown->setText(time.toString("m:ss"));。然后很容易检查是否为“ 0:00”并执行其他操作。

我希望这对您有帮助

相关问题