QTimer使用总结

QTimer四种使用方法总结

方法一:实例化对象再connect连接信号与槽

使用步骤:
(1):使用Qtimer实例化对象:

代码如下):“mainwindow.h”

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "sqlite.h"
#include <QTimer>

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
}

方法二:重写QObjiet虚函数timerEvent()

使用步骤:
(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对象,但是只会触发一次。

  • 1
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值