博客
关于我
10.QT-定时器
阅读量:442 次
发布时间:2019-03-06

本文共 1859 字,大约阅读时间需要 6 分钟。

QObject定时器

  • 需要头文件#include <QTimerEvent>

 需要函数

int QObject::startTimer(int interval);//启动定时器,启动后,就会一直定时触发timerEvent事件,设置定时器间隔时间(单位ms),启动后返回该定时器ID号.void QObject::timerEvent(QTimerEvent * event);//定时器处理函数,需要用户来重写它,如果有多个定时器,可以通过QTimerEvent::timerId()来判断定时器ID处理void killTimer(int id);//通过定时器ID号来杀掉某个定时器

示例代码

Widget.h:

#ifndef WIDGET_H#define WIDGET_H#include 
#include
class Widget : public QWidget{ Q_OBJECTprivate:virtual void timerEvent( QTimerEvent * event );public: explicit Widget(QWidget *parent = 0);};#endif // WIDGET_H

Widget.cpp:

#include "Widget.h"#include 
#include
Widget::Widget(QWidget *parent) : QWidget(parent){ int TimerID = startTimer(1000); //设置1000ms为单位 qDebug()<<"startTimerID : "<
timerId();}

 

QTimer定时器

 需要头文件#include <QTimer>  

QTimer类定时器支持单次触发和多次触发。

 

使用QTimer类定时器的步骤:

1. 创建一个QTimer定时器(示例)

QTimer *timer = new QTimer(this);

2. 连接timeout()信号与槽函数(示例)

connect(timer, SIGNAL(timeout()), this, SLOT(time_handler()));

3.启动定时器,并设置间隔时间

timer->start (int msec);               //单位ms

4.停止定时器

timer->stop();

5.删除定时器

delete timer;

 

常用函数

void   setSingleShot(bool singleShot);// 设置使能单次触发和多次触发,默认情况为多次触发bool   isActive();//判断定时器是否运行bool  setInterval ( int msec );//从新设置间隔时间

示例代码

Widget.h:

#ifndef WIDGET_H#define WIDGET_H#include 
#include
class Widget : public QWidget{ Q_OBJECT QTimer *timer;private slots: void time_handler();public: explicit Widget(QWidget *parent = 0);};#endif // WIDGET_H

Widget.cpp:

#include "Widget.h"#include 
#include
Widget::Widget(QWidget *parent) : QWidget(parent){ QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(time_handler())); timer->start(1000); //1000ms}void Widget::time_handler(){ qDebug()<<"Timer out";}

 

转载地址:http://pgiyz.baihongyu.com/

你可能感兴趣的文章
nanoGPT 教程:从零开始训练语言模型
查看>>
NASA网站曝严重漏洞,或将沦为黑客钓鱼网站?
查看>>
Nash:轻量级、安全且可靠的脚本语言
查看>>
NAS、SAN和DAS的区别
查看>>
NAS个人云存储服务器搭建
查看>>
NAS服务器有哪些优势
查看>>
NAT PAT故障排除实战指南:从原理到技巧的深度探索
查看>>
nat 网卡间数据包转发_你是不是从来没有了解过光纤网卡,它跟普通网卡有什么区别?...
查看>>
NAT-DDNS内网穿透技术,快解析DDNS的优势
查看>>
NAT-DDNS内网穿透技术,快解析DDNS的优势
查看>>
NAT-DDNS内网穿透技术,解决动态域名解析难题
查看>>
natapp搭建外网服务器
查看>>
NativePHP:使用PHP构建跨平台桌面应用的新框架
查看>>
nativescript(angular2)——ListView组件
查看>>
NativeWindow_01
查看>>
Native方式运行Fabric(非Docker方式)
查看>>
Nature | 电子学“超构器件”, 从零基础到精通,收藏这篇就够了!
查看>>
Nature和Science同时报道,新疆出土四千年前遗骸完成DNA测序,证实并非移民而是土著...
查看>>
Nature封面:只低一毫米,时间也会变慢!叶军团队首次在毫米尺度验证广义相对论...
查看>>
Nat、端口映射、内网穿透有什么区别?
查看>>