Pixiv - KiraraShss
580 字
3 分钟
QT定时器使用
在Qt中,定时器主要有两种使用方式:QTimer类 和 QObject::startTimer()。下面详细介绍这两种方法:
方法一:使用 QTimer 类(推荐)
1. 基本用法
#include <QTimer>#include <QDebug>
// 创建定时器QTimer *timer = new QTimer(this);
// 连接定时器的timeout信号到槽函数connect(timer, &QTimer::timeout, this, [](){ qDebug() << "定时器触发!";});
// 启动定时器,每隔1000毫秒触发一次timer->start(1000);2. 完整示例
class MyClass : public QObject{ Q_OBJECTpublic: MyClass(QObject *parent = nullptr) : QObject(parent) { // 创建定时器 m_timer = new QTimer(this);
// 连接信号槽 connect(m_timer, &QTimer::timeout, this, &MyClass::onTimeout);
// 设置单次定时器 // m_timer->setSingleShot(true);
// 启动定时器,2秒触发一次 m_timer->start(2000); }
private slots: void onTimeout() { qDebug() << "定时器触发,当前时间:" << QTime::currentTime();
// 可以在特定条件下停止定时器 static int count = 0; if(++count >= 5) { m_timer->stop(); qDebug() << "定时器已停止"; } }
private: QTimer *m_timer;};3. 单次定时器
// 单次定时器,只触发一次QTimer::singleShot(3000, this, [](){ qDebug() << "3秒后执行一次";});方法二:使用 QObject::startTimer()
基本用法
cpp
class MyClass : public QObject{ Q_OBJECTpublic: MyClass(QObject *parent = nullptr) : QObject(parent) { // 启动定时器,返回定时器ID m_timerId = startTimer(1000); // 1000毫秒间隔 }
protected: void timerEvent(QTimerEvent *event) override { if(event->timerId() == m_timerId) { qDebug() << "定时器事件触发"; // 处理定时任务 } }
private: int m_timerId;};常用操作
1. 启动和停止
QTimer *timer = new QTimer(this);
// 启动定时器timer->start(1000);
// 停止定时器timer->stop();
// 重新启动timer->start(500);
// 检查是否活跃if(timer->isActive()) { qDebug() << "定时器正在运行";}2. 获取和设置间隔
timer->setInterval(2000); // 设置间隔为2秒int interval = timer->interval(); // 获取当前间隔3. 在QWidget中使用
cpp
class MyWidget : public QWidget{ Q_OBJECTpublic: MyWidget(QWidget *parent = nullptr) : QWidget(parent) { QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &MyWidget::updateUI); timer->start(100); }
private slots: void updateUI() { // 更新界面 update(); }};实际应用示例
1. 数字时钟
class DigitalClock : public QLabel{ Q_OBJECTpublic: DigitalClock(QWidget *parent = nullptr) : QLabel(parent) { setAlignment(Qt::AlignCenter);
QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &DigitalClock::showTime); timer->start(1000); // 每秒更新一次
showTime(); // 立即显示时间 }
private slots: void showTime() { QTime time = QTime::currentTime(); QString text = time.toString("hh:mm:ss"); setText(text); }};2. 进度更新
class ProgressUpdater : public QObject{ Q_OBJECTpublic: ProgressUpdater(QProgressBar *progressBar, QObject *parent = nullptr) : QObject(parent), m_progressBar(progressBar) { m_timer = new QTimer(this); connect(m_timer, &QTimer::timeout, this, &ProgressUpdater::updateProgress); m_timer->start(100); // 每100毫秒更新一次 }
private slots: void updateProgress() { static int value = 0; value = (value + 1) % 101; m_progressBar->setValue(value); }
private: QTimer *m_timer; QProgressBar *m_progressBar;};支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!
最后更新于 2025-02-02,距今已过 372 天
部分内容可能已过时