Home > Blockchain >  How to properly delete QWidget from layout QT?
How to properly delete QWidget from layout QT?

Time:09-22

I know, that I can delete QWidget from QLayout so:

        QLayoutItem*item = wlay->takeAt(0);
        wlay->removeItem(item);
        delete item;
        delete w; 

However, without deleting QWidget(delete w), the widget will be on the screen. However, I cant delete the widget, so the widget will be on the screen. How to delete the widget from screen after removing it from layout? For example, I have so code:

class QTest: public QWidget{
    Q_OBJECT

    QVBoxLayout* wlay;
    QPushButton* b;
public:
    QTest(){
        wlay = new QVBoxLayout();
        b = new QPushButton("click");
        for(int i = 0; i < 20; i  )
            wlay->addWidget(new QLabel( "TEST"   QString::number(i)));
        wlay->addWidget(b);
        this->setLayout(wlay);
        connect(b, &QPushButton::clicked, this, &QTest::doit);
    }
public slots:
    void doit();
};
void QTest::doit(){
    //Removing all QLabel from Layout
    for(int i =0; i < 20; i  ){
        QLayoutItem*item = wlay->takeAt(0);
        wlay->removeItem(item);
        delete item;
    }
}

Before removing labels After removing labels

After removing QLabels from layout, labels are showed on screen. How to remove them from main Widget(without deleting them)?

CodePudding user response:

It seems the function you're looking for is QWidget::hide().


Moreover, once you've called QLayout::takeAt(), you don't have to call QLayout::removeItem() afterwards since the former already removes the item as mentioned in the documentation.

You can see QLayout::takeAt() as a shorthand for QLayout::itemAt() QLayout::removeItem().

  •  Tags:  
  • c qt
  • Related