简体   繁体   中英

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;

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, eg in your window/dialog constructor.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM