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;
    }
}
相关推荐
fzb5QsS1p18 小时前
告别重复造轮子,Qt 快速开发脚手架
开发语言·qt·php
森G19 小时前
58、最佳实践与注意事项---------多线程、竟态条件和同步
c++·qt
小樱花的樱花19 小时前
1 项目概述
开发语言·c++·qt·ui
MinterFusion20 小时前
如何在openKylin 2.0 SP2中安装Qt(v0.2.2)(上)
开发语言·qt·软件开发·系统维护·明德融创·openkylin
特立独行的猫a21 小时前
HarmonyOS鸿蒙PC的QT应用开发:(一、开发环境搭建及第一个HelloWorld)
qt·华为·harmonyos·鸿蒙pc
青花瓷21 小时前
采用QT下MingW编译opencv4.8.1
开发语言·qt
cpp_learners1 天前
Linux ARM架构 使用 linuxdeployqt 打包QT程序
linux·arm开发·qt
森G1 天前
3.1、移植Qt程序到ARM平台----移植Qt程序到ARM平台(扩展)
arm开发·c++·qt
白杆杆红伞伞1 天前
Qt Event
开发语言·qt
Magic--1 天前
Qt 桌面计算器项目
开发语言·qt