#include "widget.h" #include "ui_widget.h" #include <QTime> Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); //显示系统时间 //实例化对象 this->timer=new QTimer(this); QString curtime=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); //信号和槽函数关联 connect(this->timer,&QTimer::timeout,this,&Widget::update_time); //启动定时器 this->timer->start(1000); //计时 this->timer->start(1000); this->count=0; QTime time(0,0,0,0); //QTime转换成QString QString sec=time.addSecs(this->count).toString("mm:ss"); //更新到LCDNumber显示 this->ui->lcdNumber->display(sec); //实例化 this->timer=new QTimer(this); //信号和参函数关联 connect(this->timer,&QTimer::timeout,this,&Widget::update_time); } Widget::~Widget() { delete ui; } void Widget::on_home_btn_clicked() { //首页 } void Widget::on_per_btn_clicked() { //上一页 } void Widget::on_next_btn_clicked() { //下一页 } void Widget::on_last_btn_clicked() { //尾页 } void Widget::update_time() { //获取系统时间 QString curtime=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); //显示 this->ui->time_lab->setText(curtime); } void Widget::update_time2() { //计时 this->count++; QTime time(0,0,0,0); //QTime转换成QString QString sec=time.addSecs(this->count).toString("mm:ss"); //更新到LCDNumber显示 this->ui->lcdNumber->display(sec); }修改代码让程序运行后直接启动倒计时
时间: 2023-06-19 17:03:19 浏览: 76
你可以将启动计时器和更新LCDNumber的代码放到Widget构造函数中,然后将update_time2()函数删除,这样程序运行后就直接启动倒计时了。
修改后的代码如下:
```
#include "widget.h"
#include "ui_widget.h"
#include <QTime>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//显示系统时间
QString curtime=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
this->ui->time_lab->setText(curtime);
//启动定时器
this->timer=new QTimer(this);
connect(this->timer,&QTimer::timeout,this,&Widget::update_time);
this->timer->start(1000);
//启动倒计时
this->count=0;
this->timer2=new QTimer(this);
connect(this->timer2,&QTimer::timeout,this,&Widget::update_time2);
this->timer2->start(1000);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_home_btn_clicked()
{
//首页
}
void Widget::on_per_btn_clicked()
{
//上一页
}
void Widget::on_next_btn_clicked()
{
//下一页
}
void Widget::on_last_btn_clicked()
{
//尾页
}
void Widget::update_time()
{
//获取系统时间
QString curtime=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
//显示
this->ui->time_lab->setText(curtime);
}
void Widget::update_time2()
{
//计时
this->count++;
QTime time(0,0,0,0);
//QTime转换成QString
QString sec=time.addSecs(this->count).toString("mm:ss");
//更新到LCDNumber显示
this->ui->lcdNumber->display(sec);
}
```
注意,需要在Widget类中添加一个私有成员变量QTimer *timer2;来代表倒计时用的定时器。