场景需求:左边设置一个开始时间,点击开始按钮,右边开始倒计时,暂停按钮控制倒计时的暂停和继续。
实现:
pgsystem.h头文件中加入:
private:
QDateTimeEdit *pgtimeline;
QTimer *pgtimer1000;
QLCDNumber *lcdNumber;
static int min;//声明静态全局变量
static int sec;
static bool clicked;
private slots:
void pgxtupdateTime1000();
void starttime();
void stoptime();
pgsystem.cpp源文件中加入:
pgtimeline=new QDateTimeEdit(this);
pgtimeline->setDisplayFormat("mm分ss秒");
lcdNumber=new QLCDNumber(this);
lcdNumber->setDigitCount(8);
lcdNumber->setSegmentStyle(QLCDNumber::Flat);
lcdNumber->display("0");
pgtimer1000=new QTimer;
connect(beginBtn,&QPushButton::clicked,this,&pgsystem::starttime);//开始按钮槽函数
connect(stopBtn,&QPushButton::clicked,this,&pgsystem::stoptime);//暂停按钮槽函数
connect(pgtimer1000,&QTimer::timeout,this,&pgsystem::pgxtupdateTime1000);//倒计时更新
//开始按钮槽函数
int pgsystem::min=0;
int pgsystem::sec=0;
void pgsystem::starttime()
{
QString strMinute = pgtimeline->sectionText(QDateTimeEdit::MinuteSection);
QString strSecond = pgtimeline->sectionText(QDateTimeEdit::SecondSection);
min=strMinute.toInt();
sec=strSecond.toInt();
pgtimer1000->start(1000);
}
//暂停按钮槽函数
bool pgsystem::clicked = false;
void pgsystem::stoptime()
{
QString button_style="QPushButton{background-color:#4682B4;color:white}";
QString button_style2="QPushButton:pressed{background-color:white;color:#4682B4;border-style:inset;}";
if(clicked == false)//表示倒计时器处于运行状态,单击之后按钮状态变成“继续”
{
stopBtn->setText(QString::fromUtf8("继续"));
stopBtn->setStyleSheet(button_style2);
pgtimer1000->stop();
clicked = true;
}
else if(clicked == true)//表示倒计时器处于运行状态,单击之后按钮状态变成“暂停”
{
{
stopBtn->setText(QString::fromUtf8("暂停"));
stopBtn->setStyleSheet(button_style);
pgtimer1000->start(1000);
clicked = false;
}
}
//倒计时器槽函数
void pgsystem::pgxtupdateTime1000()
{
if (sec!=0)
{
sec=sec-1;
}
else if (min!=0)
{
sec=59;
min=min-1;
}
else
pgtimer1000->stop();//分和秒都为0时,停止计时器
lcdNumber->display(QString("%1:%2").arg(QString::number(min)).arg(QString::number(sec)));
}