Qt - remove all widgets from layout?

前端 未结 12 640
野性不改
野性不改 2020-12-01 01:33

This doesn\'t seem easy. Basically, I add QPushButtons through a function to a layout, and when the function executes, I want to clear the layout first (removi

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 02:35

    I have a possible solution for this problem (see Qt - Clear all widgets from inside a QWidget's layout). Delete all widgets and layouts in two seperate steps.

    Step 1: Delete all widgets

        QList< QWidget* > children;
        do
        {
           children = MYTOPWIDGET->findChildren< QWidget* >();
           if ( children.count() == 0 )
               break;
           delete children.at( 0 );
        }
        while ( true );
    

    Step 2: Delete all layouts

        if ( MYTOPWIDGET->layout() )
        {
            QLayoutItem* p_item;
            while ( ( p_item = MYTOPWIDGET->layout()->takeAt( 0 ) ) != nullptr )
                delete p_item;
            delete MYTOPWIDGET->layout();
        }
    

    After step 2 your MYTOPWIDGET should be clean.

提交回复
热议问题