Important: Please read the Qt Code of Conduct -

[SOLVED] Clear widget layout and repaint with a new one

  • Hey everybody!

            I have a widget with a set layout at the start of the application. I want to repaint the widget with a new layout on the click of a button. I tried the solutions given "here": and "here": but it was of no avail. 

    Please help! Thanks.

  • If you don't plan on using the same items in the new layout you can use the QStackedLayout class. Otherwise create a new layout, add your items to the new layout, delete whatever is remaining of the first layouts items, delete the widget->layout() and then call widget->setLayout with the new layout you created.

  • [quote author="b1gsnak3" date="1360229661"]Otherwise create a new layout, add your items to the new layout[/quote]

    That's what I tried to do but the layout is not getting cleared. Here's my code

    QHBoxLayout *hlayout = new QHBoxLayout();
    QVBoxLayout *vlayout = new QVBoxLayout();



    if(keyEvent->key()==Qt::Key_Down) //If the down arrow key is press
    delete MainLabel->layout();

  • Well, it's not cleared because you are using different items (label3, 4). If you wanted the same items (label1, 2) then it would've been cleared. However, for this, you should use QStackedLayout and change the index of the layout (0 for your hLayout and 1 for vLayout, for example). If you really want to use this model, then try using:

    delete MainLabel->layout();
    label3 = new QLabel();
    label4 = new QLabel();

  • Thanks a lot for your answer, b1gsnak3. qDeleteAll did the trick. Thanks again! :)

  • your welcome :) mark the topic with solved then :)

  • Oh yes! I forgot. Sorry.

  • Since the layout is itself a child of the widget it manages, you should be able to just use qDeleteAll(MainLabel->children()) and drop the delete MainLabel->layout() call.

Log in to reply