QT QTimer

Part1:简介

QTimer是 Qt 提供的一个实现定时器的定时功能的类;

QTimer还提供了一个简单的只有一次定时的函数singleShot()。一个定时器在100ms后触发处理函数animateTimeout()并且只触发一次。代码如下:

QTimer::singleShot( 100,this, SLOT(animateTimeout()) );

Part2: 简单使用:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtCore/QThread>
#include <QtCore/QTime>
#include <QtCore/QTimer>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_start_clicked();

    void on_stop_clicked();

    void slot_time();

private:
    Ui::MainWindow *ui;

private:
    QTimer *m_timer ;
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_timer = new QTimer ;
    connect(m_timer , SIGNAL(timeout()) , this , SLOT(slot_time()),Qt::DirectConnection) ;

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_start_clicked()
{
    qDebug()<<"main  thread ID: "<<QThread::currentThreadId();
     m_timer->start(1000) ;
}

void MainWindow::on_stop_clicked()
{

}
void MainWindow::slot_time()
{
    QTime mytime = QTime::currentTime() ;

     qDebug()<<"timer thread ID: "<<QThread::currentThreadId();

}

运行:

main    thread ID:  0x47cc
timer thread ID:  0x47cc
timer thread ID:  0x47cc
timer thread ID:  0x47cc
timer thread ID:  0x47cc

注意:定时器和主线程是在一个线程中,并不是多线程运行的;这里要注意;

如果堵塞了主线程,定时器肯定也不会回调了;

主要API 介绍:

a.void timeout ()定时器超时后,这个信号被发射。
b.void start()开启定时器,它的重载函数void start(int msec),启动或重新启动一个超时时间间隔为毫秒的定时器,如果定时器正在运行,它将被停止和重新启动。
c.void stop()停止定时器.
d.void setInterval(int msec)设置超时间隔(毫秒为单位)


 QTimer 使用多线程

    QThread * m_pThread;

     QTimer *m_pTimer;
 m_pThread = new QThread(this);
    m_pTimer = new QTimer();
    m_pTimer->moveToThread(m_pThread);
    m_pTimer->setInterval(2000);
    connect(m_pThread, SIGNAL(started()), m_pTimer, SLOT(start()));
    connect(m_pTimer, &QTimer::timeout, this, &MainWindow::timeOutSlot, Qt::DirectConnection);


     m_pThread->start();



void MainWindow::timeOutSlot()
{
   qDebug()<<"timer sub thread ID: "<<QThread::currentThreadId();
}

运行:

main  thread ID:  0x4720
timer sub thread ID:  0x4b98
timer sub thread ID:  0x4b98
timer sub thread ID:  0x4b98

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

恋恋西风

up up up

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值