官方解释:
The QTimer class provides repetitive and single-shot timers
这个类提供了可重复的和单次的定时器。
QTimer类为定时器提供了高级编程接口。
使用:
- 创建一个QTimer
- 将timeout()信号连接到适当的槽,然后调用start()。
- 完成1,2步后,它会以恒定的时间间隔发出timeout()信号。
例如:
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &Home::func());
timer->start(1000);
从start()后,每秒都会调用槽update()
简单实例,【倒计时软件】
头文件:
#ifndef HOME_H
#define HOME_H
#include <QWidget>
#include <QTimer>
#include <QDebug>
#include <QString>
#include <string>
#include <thread>
QT_BEGIN_NAMESPACE
namespace Ui { class Home; }
QT_END_NAMESPACE
class Home : public QWidget
{
Q_OBJECT
public:
Home(QWidget *parent = nullptr);
~Home();
void changeText(); // 修改显示的文本信息
void startCountDown(); // 开始倒计时
void text(); // 将输入框的数值显示
private:
Ui::Home *ui;
QTimer *time;
bool isActive; // 用来保存倒计时工具状态
int seconds; // 用来保存倒数时间
};
#endif // HOME_H
cpp文件:
#include "home.h"
#include "./ui_home.h"
#include <QMessageBox>
Home::Home(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Home)
{
ui->setupUi(this);
QLineEdit *line = ui->input;
time = new QTimer(this);
this->setWindowTitle("Jev_0987:倒计时软件");
line->setPlaceholderText("10");
line->setMaxLength(4);
line->setText("0");
Home::isActive = false; // 用来确认当前是否已经开始倒计时了
connect(ui->input, &QLineEdit::textEdited, this, &Home::text);
connect(ui->button, &QPushButton::clicked, this, &Home::startCountDown);
connect(time, &QTimer::timeout, this, &Home::changeText); // 绑定定时器信号
}
void Home::startCountDown(){
bool ok;
int newSeconds = ui->input->text().toInt(&ok);
qDebug()<<"点击按钮";
if(ok)
{
ui->distplay->setText(QString::number(newSeconds));
if(isActive)
{
// 上一个倒计时还没结束
time->stop();
isActive = false;
qDebug()<<"关闭上一个定时器";
}
seconds = newSeconds;
qDebug() << "startCountDown" << seconds;
isActive = true;
time->start(1000);
}else
{
qDebug() << "数据类型转换失败";
}
}
void Home::changeText()
{
qDebug()<< "changeText: " <<seconds;
seconds--;
ui->distplay->setText(QString::number(seconds));
if(seconds <= 0)
{
qDebug() << "时间到" << seconds;
ui->distplay->setText("时间到");
time->stop();
isActive = false;
}
}
void Home::text()
{
ui->distplay->setText(ui->input->text());
}
Home::~Home()
{
delete ui;
delete time;
}
main文件:
#include "home.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Home w;
w.show();
return a.exec();
}
总结遇到的问题:
(1)定时器信号连接的函数写到了button的槽函数当中,造成了多次绑定定时器信号。
(2)处理重复点击同个按钮恢复状态。