Qt: How to force a hidden widget to calculate its layout?

前端 未结 6 745
北海茫月
北海茫月 2020-12-09 17:01

What I am trying to do is render a qwidget onto a different window (manually using a QPainter)

I have a QWidget (w) with a layout and a bunch of child controls. w i

6条回答
  •  伪装坚强ぢ
    2020-12-09 17:36

    When going through QWidget::grab() I noticed this part:

    if (r.width() < 0 || r.height() < 0) {
        // For grabbing widgets that haven't been shown yet,
        // we trigger the layouting mechanism to determine the widget's size.
        r = d->prepareToRender(QRegion(), renderFlags).boundingRect();
        r.setTopLeft(rectangle.topLeft());
    }
    

    QWidget::grab() has been introduced in Qt 5.0, and this test function with a QDialog containing a layout seems to work on Qt 5.5.1

    int layoutTest_2(QApplication& a)
    {
        CLayoutTestDlg dlg; // initial dlg size can also be set in the constructor
            // https://stackoverflow.com/questions/21635427
    
        QPixmap pixmap = dlg.grab(); // must be called with default/negative-size QRect
        bool savedOK = pixmap.save("E:/temp/dlg_img.png");
            // saving is not necessary, but by now the layout should be done
    
        dlg.show();
        return a.exec();
    }
    

提交回复
热议问题