Qt06定时器
发表于更新于
字数总计:649阅读时长:2分钟阅读量: 济宁
QtQt学习Qt06定时器
wypQt中有两种方法来使用定时器,一种是定时器事件,另一种是使用信号和槽。
常使用信号和槽(代码看起来比较整洁)但是当使用多个定时器的时候最好用定时器事件来处理。
定时器方式一:定时器事件
需要: #include
方式:
- 利用对void timerEvent(QTimerEvent* e)事件的重写。
- 启动定时器 int QObject::startTimer ( int interval ) ;
开启一个定时器,返回值为int类型。他的参数interval是毫秒级别。当开启成功后会返回这个定时器的ID, 并且每隔interval 时间后会进入timerEvent 函数。直到定时器被杀死(killTimer)
- timerEvent的返回值是定时器的唯一标识。可以和e->timerId比较
- void killTimer(int id); //停止 ID 为 id 的计时器,ID 由 startTimer()函数返回
实例:在两个label中自动计数,一个间隔为1秒,一个为2秒。
- 在头文件中先声明void timerEvent(QTimerEvent* e)事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <QtWidgets/QWidget> #include "ui_Qtcontrol.h"
class Qtcontrol : public QWidget { Q_OBJECT
public: Qtcontrol(QWidget *parent = Q_NULLPTR); void timerEvent(QTimerEvent* e); int ID1; int ID2; private: Ui::QtcontrolClass ui;
};
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include "Qtcontrol.h" Qtcontrol::Qtcontrol(QWidget *parent) : QWidget(parent) { ui.setupUi(this); ID1= startTimer(1000);
ID2 = startTimer(2000); }
void Qtcontrol::timerEvent(QTimerEvent* e) { if (e->timerId()==ID1) { static int num = 1; ui.label->setText(QString::number(num++)); } if (e->timerId()==ID2) { static int num = 1; ui.label_2 ->setText(QString::number(num++)); } }
|
由于所有的事件都重写在了timerEvent中,因此当需要多个定时器时,可以用定时器的ID去对应timerEvent中的事件。
定时器方式二:QTimer类(信号与槽)
需要 : #include
方式:
- 利用定时器类QTimer
- 创建定时器对象 QTimer *timer=new QTimer(this)
- 启动定时器timer->start( 500) //参数:每隔n毫秒发送一个信号(timeout)
- 用connect连接信号和槽函数(自定义槽)
- 暂停 timer->stop
实例:启动label 每隔0.5秒计时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include "Qtcontrol.h" #include"qtimer.h" Qtcontrol::Qtcontrol(QWidget *parent) : QWidget(parent) { ui.setupUi(this);
QTimer* timer = new QTimer(this);
timer->start(500); connect(timer, &QTimer::timeout, [=]() { static int num = 1; ui.label->setText(QString::number(num++)); }); }
|
转载自:唯有自己强大 如有侵权,在下方评论 立刻删除。