QStackedWidget采用堆栈的思想,将不同的widget通过addwidget()函数放进该类的对象中,并默认编号,也可显式编号,默认从0开始。
indexOf()函数获取显示widget的页号或编号
setCurrentIndex(int) 来显示该页号的widget。
nice~
实例来一发
(1)效果图
效果图1
效果图2
(2)代码实现
.h文件:
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include<QListWidget> #include<QStackedWidget> #include<QTableWidget> class Dialog : public QDialog { Q_OBJECT public: Dialog(QWidget *parent = 0); ~Dialog(); private: QListWidget *listwidget; QStackedWidget *stackedwidget; QTableWidget *tablewidget1; QTableWidget *tablewidget2; QTableWidget *tablewidget3; }; #endif // DIALOG_H
.cpp文件:
#include "dialog.h" #include<QHBoxLayout> Dialog::Dialog(QWidget *parent) : QDialog(parent) { listwidget = new QListWidget; listwidget->addItem(tr("tablewidget1")); listwidget->addItem(tr("tablewidget2")); listwidget->addItem(tr("tablewidget3")); tablewidget1 = new QTableWidget(2, 2, 0); tablewidget2 = new QTableWidget(4, 4, 0); tablewidget3 = new QTableWidget(8, 8, 0); stackedwidget = new QStackedWidget; stackedwidget->addWidget(tablewidget1); stackedwidget->addWidget(tablewidget2); stackedwidget->addWidget(tablewidget3); QHBoxLayout *h_layout = new QHBoxLayout; h_layout->addWidget(listwidget); h_layout->addWidget(stackedwidget); h_layout->setStretchFactor(listwidget, 1); h_layout->setStretchFactor(stackedwidget, 8); setLayout(h_layout); setWindowTitle(tr("QStackedWidget Test")); setFixedSize(950, 300); QObject::connect(listwidget, SIGNAL(currentRowChanged(int)), stackedwidget, SLOT(setCurrentIndex(int))); } Dialog::~Dialog() { }
main():
#include "dialog.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Dialog w; w.show(); return a.exec(); }
(3)补充说明
1、QStackedWidget里装了3个QTableWidget对象,分别是2X2,4X4, 8X8
2、
#include<QListWidget>
#include<QStackedWidget>
这个两个头文件不可少
3、 通过调用QHBoxLayout的函数setStrechFactor()来缩放和拉伸控件。
4、<<C++ GUI QT 4>>中用另一种方法:
stackedLayout = new QStackedLayout;
stackedLayout->addWidget(appearancePage);
stackedLayout->addWidget(webBrowserPage);
stackedLayout->addWidget(mailAndNewsPage);
stackedLayout->addWidget(advancedPage);
通过QStackedWidget类中的QStackedLayout 分组布局来管理widget,效果一样