Qt 中 QWidget 的模糊效果

2021-12-09 00:00:00 qt c++

有没有办法在 Qt 中模糊一个小部件?例如,假设我想创建一个正在加载..."对话框并模糊背景(非活动窗口).

Is there any way to blur a widget in Qt? For instance, supose I want to create a 'Loading...' dialog and blur the background (not active window).

推荐答案

这个答案是在我与叠加层相关的一系列答案中:第一、第二、第三个.

This answer is in a series of my overlay-related answers: first, second, third.

如果您希望它在所有平台上运行,则需要小心.您不能将效果直接应用于顶级窗口.层次结构需要如下所示:

It requires some care if you wish for it to work on all platforms. You can't apply effects directly to top-level windows. The hierarchy needs to look as follows:

ContainerWidget
     |
     +----------+
     |          |
**Target**   Overlay

您将效果应用到 Target 小部件(例如,QMainWindow).ContainerWidget 是一个帮助器类,它使子组件占据小部件的整个尺寸.这消除了对显式零边距布局的需要.

You apply the effect to the Target widget (say, a QMainWindow). The ContainerWidget is a helper class that keeps the children occupying the full size of the widget. This obviates the need for an explicit zero-margin layout.

即使在 Mac 上也可以使用以下方法.它不会,如果您放弃了 ContainerWidget.不幸的是,这仅适用于 Qt 5.在 Qt 4 上,您的跨平台"支持不包括 Mac :( 在使用 Qt 4 (4.8.5) 或 Qt 5 的 Windows 上运行正常.

The below works, even on a Mac. It wouldn't, had you foregone the ContainerWidget. This works portably on Qt 5 only, unfortunately. On Qt 4, your "cross platform" support excludes Mac :( It works OK on Windows using either Qt 4 (4.8.5) or Qt 5.

// https://github.com/KubaO/stackoverflown/tree/master/questions/overlay-blur-19383427
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#endif

class OverlayWidget : public QWidget {
   void newParent() {
      if (!parent()) return;
      parent()->installEventFilter(this);
      raise();
   }
public:
   explicit OverlayWidget(QWidget *parent = {}) : QWidget(parent) {
      setAttribute(Qt::WA_NoSystemBackground);
      setAttribute(Qt::WA_TransparentForMouseEvents);
      newParent();
   }
protected:
   //! Catches resize and child events from the parent widget
   bool eventFilter(QObject *obj, QEvent *ev) override {
      if (obj == parent()) {
         if (ev->type() == QEvent::Resize)
            resize(static_cast<QResizeEvent*>(ev)->size());
         else if (ev->type() == QEvent::ChildAdded)
            raise();
      }
      return QWidget::eventFilter(obj, ev);
   }
   //! Tracks parent widget changes
   bool event(QEvent *ev) override {
      if (ev->type() == QEvent::ParentAboutToChange) {
         if (parent()) parent()->removeEventFilter(this);
      }
      else if (ev->type() == QEvent::ParentChange)
         newParent();
      return QWidget::event(ev);
   }
};

class ContainerWidget : public QWidget
{
public:
   explicit ContainerWidget(QWidget *parent = {}) : QWidget(parent) {}
   void setSize(QObject *obj) {
      if (obj->isWidgetType()) static_cast<QWidget*>(obj)->setGeometry(rect());
   }
protected:
   //! Resizes children to fill the extent of this widget
   bool event(QEvent *ev) override {
      if (ev->type() == QEvent::ChildAdded) {
         setSize(static_cast<QChildEvent*>(ev)->child());
      }
      return QWidget::event(ev);
   }
   //! Keeps the children appropriately sized
   void resizeEvent(QResizeEvent *) override {
      for(auto obj : children()) setSize(obj);
   }
};

class LoadingOverlay : public OverlayWidget
{
public:
   LoadingOverlay(QWidget *parent = {}) : OverlayWidget{parent} {
      setAttribute(Qt::WA_TranslucentBackground);
   }
protected:
   void paintEvent(QPaintEvent *) override {
      QPainter p{this};
      p.fillRect(rect(), {100, 100, 100, 128});
      p.setPen({200, 200, 255});
      p.setFont({"arial,helvetica", 48});
      p.drawText(rect(), "Loading...", Qt::AlignHCenter | Qt::AlignTop);
   }
};

namespace compat {
#if QT_VERSION >= QT_VERSION_CHECK(5,4,0)
using QT_PREPEND_NAMESPACE(QTimer);
#else
using Q_QTimer = QT_PREPEND_NAMESPACE(QTimer);
class QTimer : public Q_QTimer {
public:
   QTimer(QTimer *parent = nullptr) : Q_QTimer(parent) {}
   template <typename F> static void singleShot(int period, F &&fun) {
      struct Helper : public QObject {
         F fun;
         QBasicTimer timer;
         void timerEvent(QTimerEvent *event) override {
            if (event->timerId() != timer.timerId()) return;
            fun();
            deleteLater();
         }
         Helper(int period, F &&fun) : fun(std::forward<F>(fun)) {
            timer.start(period, this);
         }
      };
      new Helper(period, std::forward<F>(fun));
   }
};
#endif
}

int main(int argc, char *argv[])
{
   QApplication a{argc, argv};
   ContainerWidget base;
   QLabel label("Dewey, Cheatem and Howe, LLC.", &base);
   label.setFont({"times,times new roman", 32});
   label.setAlignment(Qt::AlignCenter);
   label.setGraphicsEffect(new QGraphicsBlurEffect);
   LoadingOverlay overlay(&base);
   base.show();
   compat::QTimer::singleShot(2000, [&]{
      overlay.hide();
      label.setGraphicsEffect({});
   });
   return a.exec();
}

相关文章