使用步骤:
(1):使用Qtimer实例化对象:
代码如下):“mainwindow.h”
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include "sqlite.h"
#include
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
protected:
private:
private:
Ui::MainWindow *ui;
QTimer *m_timer;//实例化对象
private slots:
void Timeout();
};
#endif // MAINWINDOW_H
(1):connect连接信号与槽函数:
代码如下:“mainwindow.cpp”
#pragma execution_character_set("utf-8")
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_timer =new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(Timeout()));
//operationSQLite();
}
(3):槽函数实现:
代码如下:“mainwindow.cpp”
void MainWindow::Timeout()
{
//do something
}
使用步骤:
(1)重写虚函数
代码如下:“mainwindow.h”
protected:
void timerEvent(QTimerEvent *event);
(2)调用startTimer()开启定时器保存定时器ID
代码如下:“mainwindow.cpp”
int m_timerID=this->startTimer(1000);
(3)在timerEvent()中判断是那个定时器ID发出timeout()信号
代码如下:“mainwindow.cpp”
void MainWindow::timerEvent(QTimerEvent *event)
{
if(event->timerId()==m_timerID)
{
//do something
}
else if(event->timerId()==m_timerID2)
{
//do something2
}
else if(event->timerId()==m_timerID3)
{
//do something3
}
.......//可判断多个定时器
}
使用步骤:
(1)实例化一个QTimer
代码如下:“mainwindow.h”
QTimer m_demoTimer;
(2)设置触发模式,超时时间
代码如下:“mainwindow.cpp”
m_demoTimer.setSingleShot(false);//true单次触发则在setInterval之后只运行一次,false则每隔setInterval之后运行一次
m_demoTimer.setInterval(2000);//设置超时时间为2秒
(3)连接信号和自定义槽
代码如下:“mainwindow.cpp”
connect(&m_demoTimer, &QTimer::timeout, this, 自定义的槽函数);
m_demoTimer.start();
使用此函数非常方便,因为不需要费心处理timerEvent,和start(),stop()等。
使用步骤:
(1)调用singleShot
代码如下:“mainwindow.h”
QTimer::singleShot(600000, this, SLOT(自定义的槽函数));
使用此函数非常方便,因为不需要费心处理timerEvent或创建本地QTimer对象,但是只会触发一次。