QToolBox
是 Qt 框架中的一個控件,用于創建一個可折疊的“工具箱”界面(類似 Windows 資源管理器的側邊欄)。每個子項可以展開或折疊,適合用于分組顯示多個功能模塊。以下是其基本用法和示例:
1. 基本用法
創建并添加子項
#include <QToolBox>
#include <QLabel>
#include <QPushButton>// 創建 QToolBox 對象
QToolBox *toolBox = new QToolBox(parent);// 添加子項(頁面)
QWidget *page1 = new QWidget;
QLabel *label1 = new QLabel("Page 1 Content");
QPushButton *button1 = new QPushButton("Button 1");// 將控件添加到 page1 的布局中
QVBoxLayout *layout1 = new QVBoxLayout(page1);
layout1->addWidget(label1);
layout1->addWidget(button1);// 將 page1 添加到 toolBox 并設置標題
toolBox->addItem(page1, "Page 1");// 添加第二個頁面
QWidget *page2 = new QWidget;
QLabel *label2 = new QLabel("Page 2 Content");
QVBoxLayout *layout2 = new QVBoxLayout(page2);
layout2->addWidget(label2);
toolBox->addItem(page2, "Page 2");
2. 關鍵功能
切換當前頁面
// 切換到索引為 1 的頁面(從 0 開始)
toolBox->setCurrentIndex(1);
獲取當前頁面索引
int currentIndex = toolBox->currentIndex();
響應頁面切換事件
// 連接信號槽:當頁面切換時觸發
connect(toolBox, &QToolBox::currentChanged, [](int index) {qDebug() << "當前頁面索引:" << index;
});
3. 樣式定制
通過 Qt 樣式表可以美化 QToolBox
:
toolBox->setStyleSheet("QToolBox::item {"" background: #f0f0f0;"" border: 1px solid #ccc;"" padding: 5px;""}""QToolBox::item:selected {"" background: #e0e0e0;""}"
);
4. 動態增刪頁面
插入頁面
QWidget *newPage = new QWidget;
toolBox->insertItem(1, newPage, "New Page");
移除頁面
// 移除索引為 1 的頁面
toolBox->removeItem(1);
5. 完整示例
#include <QApplication>
#include <QToolBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>int main(int argc, char *argv[]) {QApplication app(argc, argv);QWidget window;QVBoxLayout *mainLayout = new QVBoxLayout(&window);QToolBox *toolBox = new QToolBox;// 添加頁面 1QWidget *page1 = new QWidget;QLabel *label1 = new QLabel("This is Page 1");QPushButton *btn1 = new QPushButton("Click Me");QVBoxLayout *layout1 = new QVBoxLayout(page1);layout1->addWidget(label1);layout1->addWidget(btn1);toolBox->addItem(page1, "Page 1");// 添加頁面 2QWidget *page2 = new QWidget;QLabel *label2 = new QLabel("This is Page 2");QVBoxLayout *layout2 = new QVBoxLayout(page2);layout2->addWidget(label2);toolBox->addItem(page2, "Page 2");mainLayout->addWidget(toolBox);window.show();return app.exec();
}
注意事項
- 布局管理:每個頁面的內容需要單獨設置布局(如
QVBoxLayout
),否則控件可能無法正確顯示。 - 內存管理:刪除
QToolBox
時會自動刪除其所有子頁面。 - 信號擴展:除了
currentChanged
,還可以監聽其他信號如itemInserted(int index)
或itemRemoved(int index)
。