Qt中的延时

单次触发延时

单次触发延时是指定时器在指定的延时后触发一次,然后自动停止。这种方式非常适合只需要延时执行一次操作的场景。

cpp 复制代码
#include <QTimer>
#include <QObject>

class MyClass : public QObject {
    Q_OBJECT
public:
    MyClass() {
        QTimer::singleShot(1000, this, SLOT(onTimeout()));
    }

public slots:
    void onTimeout() {
        // 延时后的操作
    }
};
周期性触发延时

周期性触发延时是指定时器每隔一定的时间间隔就触发一次,直到显式停止。这种方式适合需要周期性执行操作的场景。

cpp 复制代码
#include <QTimer>
#include <QObject>

class MyClass : public QObject {
    Q_OBJECT
    QTimer *timer;
public:
    MyClass() {
        timer = new QTimer(this);
        connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
        timer->start(1000); // 每1000ms触发一次
    }

    ~MyClass() {
        if (timer) {
            timer->stop();
            delete timer;
        }
    }

public slots:
    void onTimeout() {
        // 延时后的操作
    }
};

QEventLoop是Qt的事件循环类,它也可以用来实现延时功能。这种方法适合于需要在延时期间阻塞当前线程的场景。

QtConcurrent是Qt的异步编程框架,它可以在不阻塞当前线程的情况下执行耗时操作

相关推荐
用户805533698034 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner4 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz9 天前
QML Hello World 入门示例
qt
xcyxiner12 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner13 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner13 天前
DicomViewer (添加模型类)3
qt
xcyxiner14 天前
DicomViewer (目录调整) 2
qt
xcyxiner14 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00616 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术16 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript