【问题标题】:Qt C++: how to add a simple countdown timer?Qt C++:如何添加一个简单的倒数计时器?
【发布时间】:2018-11-24 14:29:34
【问题描述】:

我是 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 上)。

【问题讨论】:

    标签: c++ qt timer


    【解决方案1】:

    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”并执行其他操作。

    希望对你有帮助

    【讨论】:

    • 也许代替global,让它成为一个成员变量?
    • @TrebuchetMS 是的,只是考虑使用 global 进行测试。此外,在完成其目标后停止/删除计时器,这样它就不会浪费 CPU 时间。
    • 我已经尝试过了,但我一定是做错了什么,因为我确实将计时器设置为 1:00,但没有其他任何反应。在头文件中,我添加了一个QTime *time = new QTime(0, 1, 0) 作为公共属性(以及我已经拥有的QTimer *timer)。在 cpp 文件中,我在 updateCountdown() 槽中添加了这两行:time->addSecs(-1); ui->countdown->setText(time->toString("m:ss"));。似乎我错过了一些东西,因为似乎什么都没有发生。我还尝试在 cpp 中声明 QTime* timein 标头,然后声明 time = new QTime(0, 1, 0);。我还没有尝试“何时到达 0:00”。
    • 您可以通过打印time->toString("m:ss") 来检查updateCountdown() 是否实际上每秒被调用一次。如果它被调用并且输出正确,则可能是 ui 没有正确更新。
    • 好吧,终于让它工作了,但我无法使用 QTime 构造函数。因此,我在头文件中声明了一个公共 QTime time 对象,然后在 MainWindow 构造函数中使用 time.setHMS(0,1,0) 对其进行初始化。然后,就像@LucasMota 所说,我在 updateCountdown() 插槽中调用了time=time.addSecs(-1)ui->countdown->setText(time.toString("m:ss"))。我还在 MainWindow 构造函数中将标签初始化更改为ui->countdown->setText(time.toString("m:ss"))。谢谢。
    猜你喜欢
    • 2010-11-14
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2020-12-25
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多