loadingWidget.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // loadingwidget.cpp
  2. #include "loadingwidget.h"
  3. #include <QVBoxLayout>
  4. #include <QResizeEvent>
  5. #include <QApplication>
  6. #include <QScreen>
  7. #include <QLabel>
  8. #include <QMovie>
  9. LoadingWidget* LoadingWidget::m_instance = nullptr;
  10. LoadingWidget::LoadingWidget(QWidget *parent)
  11. : QWidget(parent)
  12. {
  13. initUI();
  14. }
  15. LoadingWidget* LoadingWidget::instance()
  16. {
  17. if (!m_instance) {
  18. m_instance = new LoadingWidget();
  19. }
  20. return m_instance;
  21. }
  22. void LoadingWidget::showLoading(QWidget* parent, const QString& text)
  23. {
  24. LoadingWidget* instance = LoadingWidget::instance();
  25. // 如果提供了parent,则设置parent
  26. if (parent) {
  27. instance->setParent(parent);
  28. }
  29. instance->m_textLabel->setText(text);
  30. instance->m_movie->start();
  31. instance->updatePosition();
  32. instance->show();
  33. instance->raise();
  34. }
  35. void LoadingWidget::hideLoading()
  36. {
  37. if (m_instance) {
  38. m_instance->m_movie->stop();
  39. m_instance->hide();
  40. }
  41. }
  42. void LoadingWidget::initUI()
  43. {
  44. // 设置窗口属性
  45. setWindowFlags(Qt::FramelessWindowHint | Qt::SubWindow);
  46. setAttribute(Qt::WA_TranslucentBackground);
  47. setAttribute(Qt::WA_ShowWithoutActivating);
  48. // 创建动画
  49. m_movie = new QMovie(":/icons/icons/loading.gif");
  50. m_loadingLabel = new QLabel(this);
  51. m_loadingLabel->setMovie(m_movie);
  52. m_loadingLabel->setAlignment(Qt::AlignCenter);
  53. // 创建文本标签
  54. m_textLabel = new QLabel(this);
  55. m_textLabel->setAlignment(Qt::AlignCenter);
  56. // 布局
  57. QVBoxLayout* layout = new QVBoxLayout(this);
  58. layout->addWidget(m_loadingLabel);
  59. layout->addWidget(m_textLabel);
  60. layout->setSpacing(10);
  61. layout->setContentsMargins(50, 80, 50, 50);
  62. // 样式
  63. setStyleSheet("background-color: rgba(255, 255, 255, 0.8); border-radius: 0px;");
  64. m_textLabel->setStyleSheet("color: white; font-size: 16px;");
  65. // 初始隐藏
  66. hide();
  67. }
  68. void LoadingWidget::resizeEvent(QResizeEvent *event)
  69. {
  70. QWidget::resizeEvent(event);
  71. updatePosition();
  72. }
  73. void LoadingWidget::updatePosition()
  74. {
  75. if (parentWidget()) {
  76. // 居中显示在父窗口
  77. QRect parentRect = parentWidget()->rect();
  78. resize(parentRect.size());
  79. move(parentRect.center() - rect().center());
  80. } else {
  81. // 如果没有父窗口,居中显示在屏幕
  82. QRect screenGeometry = QApplication::primaryScreen()->geometry();
  83. resize(screenGeometry.size());
  84. move(screenGeometry.center() - rect().center());
  85. }
  86. }