QT 中 QTimer 类 备查

基础

cpp 复制代码
// 指定了父对象, 创建的堆内存可以自动析构
QTimer::QTimer(QObject *parent = nullptr);

// 根据指定的时间间隔启动或者重启定时器, 需要调用 setInterval() 设置时间间隔
void QTimer::start();

// 启动或重新启动定时器,超时间隔为msec毫秒。
void QTimer::start(int msec);

// 停止定时器。
void QTimer::stop();

//当定时器超时时,该信号就会被发射出来。
[signal] void QTimer::timeout();

// 设置定时器时间间隔为 msec 毫秒,默认值是0。
void QTimer::setInterval(int msec);

// 获取定时器的时间间隔, 返回值单位: 毫秒
int QTimer::interval() const;

设置定时器精度

cpp 复制代码
void QTimer::setTimerType(Qt::TimerType atype);	// 设置定时器的精度
参数: 
    - Qt::PreciseTimer -> 精确的精度, 毫秒级
    - Qt::CoarseTimer  -> 粗糙的精度, 和1毫秒的误差在5%的范围内, 默认精度
    - Qt::VeryCoarseTimer -> 非常粗糙的精度, 精度在1秒左右

Qt::TimerType QTimer::timerType() const;	// 获取当前定时器的精度
在这里插入代码片

其他API

cpp 复制代码
// 如果定时器正在运行,返回true; 否则返回false。
bool QTimer::isActive() const;

// 判断定时器是否只触发一次
bool QTimer::isSingleShot() const;

// 设置定时器是否只触发一次, 参数为true定时器只触发一次, 为false定时器重复触发, 默认为false
void QTimer::setSingleShot(bool singleShot);

小案列1

效果
思路
cpp 复制代码
    //设置界面实时时间
    QTimer *timer = new QTimer(this);
    timer->start(1000);//启动定时器
    connect(timer, &QTimer::timeout, [=](){
        QTime time = QTime::currentTime();//获取当前时间
        QString str = time.toString("hh:mm:ss");
        ui->label_curTime->setText(str);//显示到界面
    });

小案列2

使用QTimer类中的 全局静态 函数,实现延时。

cpp 复制代码
[static] void QTimer::singleShot(int msec, const QObject *receiver, PointerToMemberFunction method);
功能: 在 msec 毫秒后发射一次信号, 并且只发射一次
参数:
	- msec:     在msec毫秒后发射信号
	- receiver: 接收信号的对象地址
	- method:   槽函数地址
思路
cpp 复制代码
//延时300毫秒,切换窗口
QTimer::singleShot(300, this, [=](){// 延时300毫秒
    this->hide();//隐藏主窗口
    chooseScene->show();//显示其他窗口
});

其他方法使用定时器

返回定时器 Id

重写定时器事件,利用 定时器 id 判断是哪一个定时器

详细教程可转

爱编程的大丙

相关推荐
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner2 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz7 天前
QML Hello World 入门示例
qt
xcyxiner10 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner10 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner11 天前
DicomViewer (添加模型类)3
qt
xcyxiner11 天前
DicomViewer (目录调整) 2
qt
xcyxiner12 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能13 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G14 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt