不幸的是,你不能直接这样做,因为它将跨越标题小部件不占用的所有可用空间.如果您知道页面的确切高度,可以通过在QToolBox上设置
fixed height来模拟您想要的内容.但你不想在实践中这样做.
如果您想要您所要求的行为,那么您需要编写自己的自定义控件.它不一定很难.使用QVBoxLayout并填充自定义类的项目,让我们称之为ToolItem,它是一个带有标题的QWidget(可能是一个显示/隐藏的按钮)和另一个用于显示可见或不可见内容的QWidget.
以下非常简单的示例将在单击ToolItem时切换其可见性.只有在可见时它才会占据任何空间.
class ToolItem : public QWidget {
public:
ToolItem(const QString &title,QWidget *item) : item(item) {
QVBoxLayout *layout = new QVBoxLayout;
layout->setContentsMargins(0,0);
layout->addWidget(new QLabel(title));
layout->addWidget(item);
setLayout(layout);
item->setVisible(false);
}
protected:
void mousePressEvent(QMouseEvent *event) {
item->setVisible(!item->isVisible());
}
private:
QWidget *item;
};
class ToolBox : public QWidget {
public:
ToolBox() : layout(new QVBoxLayout) {
setLayout(layout);
}
void addItem(ToolItem *item) {
// Remove last spacer item if present.
int count = layout->count();
if (count > 1) {
layout->removeItem(layout->itemAt(count - 1));
}
// Add item and make sure it stretches the remaining space.
layout->addWidget(item);
layout->addStretch();
}
private:
QVBoxLayout *layout;
};
简单的用法:
QWidget *window = new QWidget;
window->setWindowTitle("QToolBox Example");
QListWidget *list = new QListWidget;
list->addItem("One");
list->addItem("Two");
list->addItem("Three");
ToolBox *toolBox = new ToolBox;
toolBox->addItem(new ToolItem("Title 1",new QLabel("Some text here")));
toolBox->addItem(new ToolItem("Title 2",list));
toolBox->addItem(new ToolItem("Title 3",new QLabel("Lorem Ipsum..")));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(toolBox);
window->setLayout(layout);
window->resize(500,500);
window->show();
如果需要,您现在可以将其调整为QToolBox.
请不要犹豫,提出后续问题.