QVBoxLayout *layout = new QVBoxLayout;
QLabel *label = new QLabel("Label");
QSpinBox *spinBox = new QSpinBox;
layout->addWidget(label);
layout->addWidget(spinBox);
QLayoutItem *item = layout->itemAt(0);
if (item) {
layout->removeItem(item);
delete item;
}
removeWidget函数的参数是QWidget类型的,可以用于从布局中移除一个控件,它返回一个bool值,表示是否成功移除控件。
从一个水平布局中移除一个按钮:
QHBoxLayout *layout = new QHBoxLayout;
QPushButton *button = new QPushButton("Button");
QLabel *label = new QLabel("Label");
layout->addWidget(button);
layout->addWidget(label);
if (layout->indexOf(button) != -1) {
layout->removeWidget(button);
button->deleteLater();
}
注意:移除控件时调用deleteLater()函数是为了避免在removeWidget函数中访问已删除的控件。