QT学习笔记-QTimer
1.QT学习笔记-信号与槽(干货)
2.QT学习笔记-QTimer
官方解释:
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()
简单实例【倒计时软件】
关于按键,显示,输入框的对象名称需要自己设置,我这里设置的为button,display,input
头文件:
#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)处理重复点击同个按钮恢复状态。
本文作者:Jev_0987
本文链接:https://www.cnblogs.com/jev-0987/p/17878464.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步