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;
    }
}
相关推荐
C++ 老炮儿的技术栈14 分钟前
Qt 编写 TcpClient 程序 详细步骤
c语言·开发语言·数据库·c++·qt·算法
打工哪有不疯的1 小时前
使用 MSYS2 为 Qt (MinGW 32/64位) 完美配置 OpenSSL
c++·qt
LYOBOYI1233 小时前
qtcpSocket详解
c++·qt
无小道5 小时前
Qt——网络编程
开发语言·qt
云中飞鸿5 小时前
VS编写QT程序,如何向linux中移植?
linux·开发语言·qt
草莓熊Lotso5 小时前
Qt 主窗口核心组件实战:菜单栏、工具栏、状态栏、浮动窗口全攻略
运维·开发语言·人工智能·python·qt·ui
云中飞鸿17 小时前
QTCreator快捷键
qt
十五年专注C++开发18 小时前
QStyleItemDelegate:自定义列表控件类神器
qt·model·view·delegate
无小道19 小时前
Qt——事件简单介绍
开发语言·前端·qt
mengzhi啊1 天前
QUndoView 本质是一个 Qt 界面控件(继承自 QListView),专门适配 QUndoStack
qt