123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- // loadingwidget.cpp
- #include "loadingwidget.h"
- #include <QVBoxLayout>
- #include <QResizeEvent>
- #include <QApplication>
- #include <QScreen>
- #include <QLabel>
- #include <QMovie>
- LoadingWidget* LoadingWidget::m_instance = nullptr;
- LoadingWidget::LoadingWidget(QWidget *parent)
- : QWidget(parent)
- {
- initUI();
- }
- LoadingWidget* LoadingWidget::instance()
- {
- if (!m_instance) {
- m_instance = new LoadingWidget();
- }
- return m_instance;
- }
- void LoadingWidget::showLoading(QWidget* parent, const QString& text)
- {
- LoadingWidget* instance = LoadingWidget::instance();
- // 如果提供了parent,则设置parent
- if (parent) {
- instance->setParent(parent);
- }
- instance->m_textLabel->setText(text);
- instance->m_movie->start();
- instance->updatePosition();
- instance->show();
- instance->raise();
- }
- void LoadingWidget::hideLoading()
- {
- if (m_instance) {
- m_instance->m_movie->stop();
- m_instance->hide();
- }
- }
- void LoadingWidget::initUI()
- {
- // 设置窗口属性
- setWindowFlags(Qt::FramelessWindowHint | Qt::SubWindow);
- setAttribute(Qt::WA_TranslucentBackground);
- setAttribute(Qt::WA_ShowWithoutActivating);
- // 创建动画
- m_movie = new QMovie(":/icons/icons/loading.gif");
- m_loadingLabel = new QLabel(this);
- m_loadingLabel->setMovie(m_movie);
- m_loadingLabel->setAlignment(Qt::AlignCenter);
- // 创建文本标签
- m_textLabel = new QLabel(this);
- m_textLabel->setAlignment(Qt::AlignCenter);
- // 布局
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->addWidget(m_loadingLabel);
- layout->addWidget(m_textLabel);
- layout->setSpacing(10);
- layout->setContentsMargins(50, 80, 50, 50);
- // 样式
- setStyleSheet("background-color: rgba(255, 255, 255, 0.8); border-radius: 0px;");
- m_textLabel->setStyleSheet("color: white; font-size: 16px;");
- // 初始隐藏
- hide();
- }
- void LoadingWidget::resizeEvent(QResizeEvent *event)
- {
- QWidget::resizeEvent(event);
- updatePosition();
- }
- void LoadingWidget::updatePosition()
- {
- if (parentWidget()) {
- // 居中显示在父窗口
- QRect parentRect = parentWidget()->rect();
- resize(parentRect.size());
- move(parentRect.center() - rect().center());
- } else {
- // 如果没有父窗口,居中显示在屏幕
- QRect screenGeometry = QApplication::primaryScreen()->geometry();
- resize(screenGeometry.size());
- move(screenGeometry.center() - rect().center());
- }
- }
|