user2366975
user2366975

Reputation: 4700

Can't add my Widget to a layout

Why can't I add my widget to the layout? It is like the example for adding Widgets... My aim is to draw into a small QWidget, whichs purpose is only to hold that painted element.

void Note::paintEvent(QPaintEvent *event)
{

    paintExample = new(QWidget);
    paintExample->setGeometry(500,500,500,500);
    paintExample->setStyleSheet("background:yellow");

    QImage *arrowImg = new QImage(100,100,QImage::Format_RGB32);
    QHBoxLayout *lay = new QHBoxLayout;
    lay->addWidget(arrowImg); //Error: no matching function for call to 'QHBoxLayout::addWidget(QImage*&)'
    paintExample->setLayout(lay);

    QPainter painter(arrowImg); //Must paint on QImage/QPixmap/QPicture, QWidget not possible?
    if (painter.isActive()){
        painter.begin(arrowImg);
        painter.setPen(Qt::black);
        QRect rect = QRect(50,25,60,40);
        painter.drawRect(rect);
        painter.end();
    }
    paintExample->show();
}

In the class header in private area:

QWidget * paintExample;

Upvotes: 1

Views: 2040

Answers (2)

Shoe
Shoe

Reputation: 76240

Why can't I add my widget to the layout?

Because QImage is not a QWidget. That's why. You should probably wrap the image in a QLabel:

QLabel arrowLabel;
arrowLabel.setPixmap(QPixmap::fromImage(*arrowImg));

and pass that to the layout:

lay->addWidget(arrowLabel);

Upvotes: 0

mike.dld
mike.dld

Reputation: 3049

Read the documentation carefully:

  • QHBoxLayout, and any other layout, could only hold items inheriting from QLayoutItem, which are QLayout itself, QSpacerItem and QWidgetItem. Create QWidget and paint on that.
  • QPainter constructor accepts descendants from QPaintDevice and QWidget is among those, so it's totally possible.

Now, to other issues:

  • You create parentless objects in paintEvent() without deleting them. Not only this method could be called quite frequently, this approach to painting is not good at all. As I understand Note is a QWidget already, so you're free to paint on it right away, with QPainter painter(this);.
  • Operations with layout are most definitely not meant to be done in paintEvent() either, as well as showing/hiding widgets. Do this somewhere else, e.g. in your window/dialog constructor.

Upvotes: 1

Related Questions