1.效果

2.代码
#ifndef LOADINGMASK_H
#define LOADINGMASK_H
#include <QWidget>
#include <QLabel>
#include <QMovie>
#include <QPainter>
#include <QApplication>
#include <QScreen>
class LoadingMask : public QWidget
{
Q_OBJECT
public:
explicit LoadingMask(QWidget* parent = nullptr) :QWidget(parent){
init();
}
// 显示遮罩
static void showMask(QWidget* parent) {
if (!parent) return;
LoadingMask* mask = new LoadingMask(parent);
mask->resize(parent->size());
mask->show();
}
// 隐藏遮罩
static void hideMask(QWidget* parent) {
if (!parent) return;
for (QWidget* child : parent->findChildren<LoadingMask*>()) {
child->deleteLater();
}
}
protected:
void paintEvent(QPaintEvent* event) override {
Q_UNUSED(event)
QPainter painter(this);
painter.fillRect(rect(), QColor(255, 255, 255, 200));
}
void resizeEvent(QResizeEvent* event) override {
Q_UNUSED(event)
if (lb_loading_) {
centerLoadingLabel();
}
}
private:
void init(){
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
lb_loading_ = new QLabel(this);
lb_loading_->setObjectName("lb_mv");
lb_loading_->setFixedSize(300, 250);
movie_ = new QMovie("D:/wait_loading.gif");
movie_->setScaledSize(lb_loading_->size());
lb_loading_->setMovie(movie_);
movie_->start();
setStyleSheet(R"(
QLabel#lb_mv{
background:grey;
}
)");
}
void centerLoadingLabel() {
if (!lb_loading_) return;
const QPoint center = rect().center();
const QSize labelSize = lb_loading_->size();
lb_loading_->move(
center.x() - labelSize.width() / 2,
center.y() - labelSize.height() / 2
);
}
private:
QLabel *lb_loading_ = nullptr;
QMovie *movie_ = nullptr;
};
#endif // LOADINGMASK_H