QPainter忽略paintEvent内部的剪辑

时间:2018-12-14 18:31:29

标签: qt qwidget clip qpainter qt4.8

我试图在QPushButton(按钮边界之外)下方绘制文本时将其聚焦。为此,我将QPushButton子类化,并在QPainter的覆盖paintEvent方法中使用QPushButton drawText方法绘制文本。在绘制之前,我将QPainter::setClipping(false)设置为启用文本来绘制侧面按钮的边界。但是以某种方式QPainter::setClipping(false)无法正常工作,并且文本不会在按钮范围之外绘制。

1 个答案:

答案 0 :(得分:3)

画家的绘画引擎本身实现了较低级别的裁剪,而小部件画家默认情况下未裁剪。换句话说:不可能关闭此剪辑。符合以下条件:

void Class::paintEvent(QPaintEvent *ev) {
  Parent::paintEvent(ev);
  QPainter p(this);
  Q_ASSERT(!p.hasClipping());
  // and now you do:
  p.setClipping(false); // this is a no-op!
}

一个简单的解决方案是添加一个小部件,该小部件将文本绘制为按钮的同级元素,并将其放置在按钮下方。该小部件可以是QLabel

static const char kLabelSibling[] = "qq_labelSibling";
static const char kTrackedSibling[] = "qq_trackedSibling";

void setTextBelow(QWidget *widget, const QString &text) {
  Q_ASSERT(widget->parent);
  class Filter : QObject {
    static QLabel *getLabel(QObject *sibling) {
      return widget->property(kLabelSibling).value<QLabel*>();
    }
    static void updateLabel(QWidget *label) {
      auto *sibling = label->property(kTrackedSibling).value<QWidget*>();
      Q_ASSERT(sibling);
      label->setParent(sibling->parent());
      label->move(sibling->bottomLeft());
      label->setVisible(sibling->hasFocus());
    }
    bool eventFilter(QObject *obj, QEvent *ev) override {
      if (auto *label = getLabel(obj))
        if (ev->type() == QEvent::Resize || ev->type() == QEvent::Move 
            || ev->type() == QEvent::ParentChange || ev->type() == QEvent::FocusIn
            || ev->type() == QEvent::FocusOut)
          updateLabel(label);
      return false;
    }
   public:
    using QObject::QObject;
  };
  auto *label = Filter::getLabel(widget);
  if (!label) {
    label = new QLabel(widget->parent());
    label->setProperty(kTrackedSibling, QVariant::fromValue(widget));
    widget->setProperty(kLabelSibling, QVariant::fromValue(label));
    widget->installEventFilter(new Filter(widget));
    QObject::connect(widget, &QObject::destroyed, label, [widget, label]{
      widget->setProperty(kLabelSibling, {});
      label->setProperty(kTrackedSibling, {});
      label->deleteLater();
    });
  }
  label->setText(text);
  Filter::updateLabel(label);
}

(对不起,以上内容未经测试并从内存写入)