Frage

I have QVBoxLayout with multiple children and I want to be able to draw on top of it. I've tried implementing paintEvent(QPaintEvent *) for the layout but everything I draw stays under the children. How can I do it? I'd be thankful for sample code.

War es hilfreich?

Lösung

Layouts don't have paintEvent member so you can't reimplement it. I'm surprised you managed to get some effect from this action.

  1. Add new QWidget (let's call it wrapper) into your form and add your QVBoxLayout into this widget.
  2. Create another widget (overlay) and add it to the wrapper using setParent(), not adding it into layout.
  3. Reimplement overlay's paintEvent or add some other widgets to the overlay.

Simple example (tested):

class MyWidget : public QWidget {
public:
  void paintEvent(QPaintEvent *e) {
    QWidget::paintEvent(e);
    QPainter p(this);
    p.fillRect(4, 4, 30, 30, QBrush(Qt::red));
  }
};

QWidget* wrapper = new QWidget();
QVBoxLayout* layout = new QVBoxLayout(wrapper);
layout->addWidget(new QLabel("test1"));
layout->addWidget(new QLabel("test2"));
MyWidget* overlay = new MyWidget();
overlay->setParent(wrapper);
wrapper->show();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top