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;
    }
}
相关推荐
Main. 242 小时前
从0到1学习Qt -- 创建项目
qt
共享家95276 小时前
QT-常用控件(多元素控件)
开发语言·前端·qt
寻找华年的锦瑟7 小时前
Qt-键鼠事件
开发语言·qt
jjjxxxhhh1238 小时前
【项目-】Qt + QCustomPlot 实现频谱监测仪:四图联动、高频信号注入、鼠标交互全解析
开发语言·qt·交互
Larry_Yanan10 小时前
QML学习笔记(四十)QML的FileDialog和FolderDialog
笔记·qt·学习
知南x11 小时前
【QT界面设计学习篇】qt Kits工具设置/qt多版本设置(ubuntu)
qt·学习·ubuntu
ajassi200012 小时前
开源 C++ QT QML 开发(二十二)多媒体--ffmpeg编码和录像
c++·qt·开源
Larry_Yanan17 小时前
QML学习笔记(四十)QML的ApplicationWindow和StackView
c++·笔记·qt·学习·ui
寻找华年的锦瑟21 小时前
Qt-配置文件(INI/JSON/XML)
开发语言·qt
gd63213741 天前
银河麒麟 aarch64 linux 里面的 qt 怎么安装kit
linux·服务器·qt