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;
    }
}
相关推荐
ShineWinsu5 小时前
对于Qt:信号量(QSemaphore)的解析
c++·qt·面试·笔试·客户端·线程安全·信号量
ShineWinsu1 天前
对于Qt:条件变量(QWaitCondition)的解析
c++·qt·面试·线程·条件变量·客户端·锁
郝学胜-神的一滴2 天前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
敲上瘾2 天前
Qt 常用控件:按钮、显示输入、容器与布局等
开发语言·c++·qt·qt6.3
ShineWinsu3 天前
对于Qt:事件分发器以及事件过滤器的解析
c++·qt·面试·gui·客户端·事件过滤器·事件分发器
ShineWinsu3 天前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
西西弗Sisyphus4 天前
Qt QML 程序是怎么跑起来的(1)qml-only
开发语言·c++·qt
小灰灰搞电子4 天前
QAccel 类讲解与代码示例:Qt 3 中的键盘加速键管理
qt·计算机外设
ShineWinsu5 天前
对于Qt:重写事件步骤的解析
开发语言·c++·qt·客户端·事件·鼠标事件·步骤
敲上瘾6 天前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui