在QDialog框内通过QLabel显示计时器

Ric*_*het -2 c++ qt qt4 timer

我正在制作一个小型GUI应用程序,我在其中创建了一个弹出对话框,提示用户按OK或CANCEL.如果用户按下OK,则会保存一些更改,如果用户按CANCEL,则会丢弃更改.

现在,我想在QLabel对象内的对话框中放一个计时器,它将显示如下 -

在此输入图像描述

在5秒内发送消息,在4秒内发送消息,.. ..在1秒内发送消息.

倒计时结束后,将考虑默认"OK",并保存所有更改.如何在GUI应用程序上实现这样的视觉效果?我的意思是实现一个concole计时器很容易,但如何通过GUI屏幕可视化计时器??? 任何帮助..

Che*_*byl 6

在构造函数中尝试:

mutable int sec = 5;//in header for example, we need mutable to use it in lambda 
//...
ui->label->setText("Sending message in 5 secs");
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this,[=]() {
    sec--;
    if(!sec)
    {
        qDebug()<< "Ok";
        timer->stop();//stop timer and do something
        //Ok
    }
    else
        ui->label->setText(QString("Sending message in %1 secs").arg(sec));
   });
    timer->start(1000);
Run Code Online (Sandbox Code Playgroud)

我这里使用的C++11(CONFIG += c++11.pro文件),信号和槽新的语法,当然,如果你愿意,你可以使用旧的语法.

用于Qt4:

ui->label->setText("Sending message in 5 secs");
timer = new QTimer(this);//class member
connect(timer, SIGNAL(timeout()), this, SLOT(slot())); 
timer->start(1000);
Run Code Online (Sandbox Code Playgroud)

在插槽中:

sec--;
if(!sec)
{
    qDebug()<< "Ok";
    timer->stop();//stop timer and do something
    //Ok
}
else
    ui->label->setText(QString("Sending message in %1 secs").arg(sec));
Run Code Online (Sandbox Code Playgroud)

sec变量可以是不可变的