简体   繁体   English

如何从布局 QT 中正确删除 QWidget?

[英]How to properly delete QWidget from layout QT?

I know, that I can delete QWidget from QLayout so:我知道,我可以从 QLayout 中删除 QWidget,这样:

        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.但是,如果不删除 QWidget(delete w),小部件将出现在屏幕上。 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;
    }
}

去除标签之前 去除标签后

After removing QLabels from layout, labels are showed on screen.从布局中删除 QLabels 后,标签会显示在屏幕上。 How to remove them from main Widget(without deleting them)?如何从主小部件中删除它们(不删除它们)?

It seems the function you're looking for is QWidget::hide() .您正在寻找的 function 似乎是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 .此外,一旦你调用QLayout::takeAt() ,你就不必再调用QLayout::removeItem()了,因为前者已经删除了文档中提到的项目。

You can see QLayout::takeAt() as a shorthand for QLayout::itemAt() + QLayout::removeItem() .您可以将QLayout::takeAt()视为QLayout::itemAt() + QLayout::removeItem()的简写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM