Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Vertical layout of custom widgets



  • I was trying to find out how to make a layout and have custom widgets vertically down just like the idea this guy did.

    https://stackoverflow.com/questions/47835951/qt-how-to-add-custom-widgets-to-a-vertical-layout-to-occupy-the-least-amount-of

    However, i tried his method and the error i keep getting is QWidget::setLayout: Attempting to set QLayout "" on MainWindow "MainWindow", which already has a layout.

    So just asking, for example i have a custom layout of 1 line edit and one pushbutton horizontally aligned, how do i make 5 of the vertically aligned together as such?
    0_1530873353490_4291520f-d9c3-4b0b-a12e-efef16b82559-image.png

    This is the last code i tried:
    QVBoxLayout* nodeVLayout = new QVBoxLayout;
    QSpacerItem* spacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding);

    for(int i=0;i<5;i++){
    Item *node=new Item;
    nodeVLayout->addWidget(node);
    nodeVLayout->addSpacerItem(spacer);
    }
    setLayout(nodeVLayout);


  • Moderators

    @GCDX
    the QMainWindow itself should never get a layout assigned. It should rather be it's centralWidget.



  • @raven-worx how do i add a layout inside the Mainwindow??



  • i tried ui->centralWidget->setLayout(nodeVLayout); and it also doesnt work



  • OH okay nvm i solved it thanks so much, you telling me the central widget helps


  • Moderators

    @GCDX
    because you already assigned a layout to your centralWidget as seen in the tree in your screenshot.
    When you then try to set another layout to an item you already specified via QtDesigner you get this warning.

    So why don't you stick to QtDesigner or QtWidgets (C++) at all?

    Alternatively you can add widgets to an existing layout without assigning a new layout.

    QVBoxLayout* vLayout = qobject_cast<QVBoxLayout*>(ui->centralWidget->layout());
    vLayout->addWidget(...);
    

    But this is error prone when you don't know what you are doing ;)


Log in to reply