GxtWaitCursor:Qt下基于RAII的鼠标等待光标类

有时我们需要以阻塞的方式执行一点耗时的操作,这时需要主窗口光标呈现忙状态,GxtWaitCursor正是为此设计;重载的构造函数,可以让光标呈现忙状态一定时间后自动恢复。

GxtWaitCursor.h

cpp 复制代码
#pragma once

#include <QObject>

//=======================================================================================
// 等待光标类
//=======================================================================================
class GxtWaitCursor : public QObject
{
    Q_OBJECT

public:
    /*
    **  构造函数:使光标进入忙录状态
    */
    GxtWaitCursor(QObject *parent = nullptr);

    /*
    **  构造函数:使光标进入忙录状态并于指定时长后恢复
    */
    GxtWaitCursor(int msec, QObject *parent = nullptr);

    /*
    **  析构函数:恢复光标
    */
    ~GxtWaitCursor();

private:
    void beginWait(int msec = 0);
    void endWait();

private:
    /*
    **  光标是否已经恢复
    */
    bool m_cursorHasRestored { false };
};

GxtWaitCursor.cpp

cpp 复制代码
#include <QTimer>
#include <QCursor>
#include <QGuiApplication>
#include "GxtWaitCursor.h"

//=======================================================================================
GxtWaitCursor::GxtWaitCursor(QObject *parent)
    : QObject(parent)
{
    beginWait();
}

//=======================================================================================
GxtWaitCursor::GxtWaitCursor(int msec, QObject *parent)
    : QObject(parent)
{
    beginWait(msec);
}

//=======================================================================================
GxtWaitCursor::~GxtWaitCursor()
{
    endWait();
}

//=======================================================================================
void GxtWaitCursor::beginWait(int msec)
{
    m_cursorHasRestored = false;

    QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

    if (msec > 0)
    {
        QTimer::singleShot(msec, [this]
        {
            if (!m_cursorHasRestored)
            {
                QGuiApplication::restoreOverrideCursor();
                m_cursorHasRestored = true;
            }
        });
    }
}

//=======================================================================================
void GxtWaitCursor::endWait()
{
    if (!m_cursorHasRestored)
    {
        QGuiApplication::restoreOverrideCursor();
        m_cursorHasRestored = true;
    }
}
相关推荐
桥田智能11 小时前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G13 小时前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
森G14 小时前
77、线程池原理和实现------服务器源码解析----云视频服务项目
服务器·c++·qt
森G15 小时前
71、打包发布---------打包发布
c++·qt
初圣魔门首席弟子15 小时前
Node.js 详细介绍(知识库版)
windows·qt·node.js·知识库
C++ 老炮儿的技术栈16 小时前
Qt工控实战:自研机器人TCP长连接客户端(粘包处理+心跳保活+自动重连完整源码解析)
qt·tcp/ip·机器人
郝学胜-神的一滴16 小时前
CMake 019:程序生成与清理全解析
开发语言·c++·qt·程序人生·软件构建·cmake
森G17 小时前
76、仿ASIO实现的Linux c++服务器------服务器源码解析----云视频服务项目
c++·qt
superkcl202217 小时前
【QT Thread】
c++·qt
CodeKwang17 小时前
Windows 环境 OCCT 8.0 编译构建及与 Qt6 项目集成
windows·qt·opencascade