Qt使用QStackedWidget實現堆棧窗口


 

Qt使用QStackedWidget實現堆棧窗口

分類: QT

堆棧窗口可以根據選擇項的不同顯示不同的窗體

 

 

[cpp]  view plain copy print ?
 
  1. // stackeddlg.h  
  2. #ifndef STACKEDDLG_H  
  3. #define STACKEDDLG_H  
  4.   
  5. #include <QDialog>  
  6. #include <QLabel>  
  7. #include <QListWidget>  
  8. #include <QStackedWidget>  
  9.   
  10. class StackedDlg : public QDialog  
  11. {  
  12.     Q_OBJECT  
  13. public:  
  14.     explicit StackedDlg(QWidget *parent = 0);  
  15. signals:  
  16. public slots:  
  17.   
  18. private:  
  19.     QLabel *textLabel;  
  20.     QLabel *showLabel;  
  21.     QLabel *aboutLabel;  
  22.     QListWidget *list;  
  23.     QStackedWidget *stack;  
  24. };  
  25. #endif // STACKEDDLG_H  


 

[cpp]  view plain copy print ?
 
  1. //stackeddlg.cpp  
  2. #include "stackeddlg.h"  
  3. #include <QHBoxLayout>  
  4.   
  5. StackedDlg::StackedDlg(QWidget *parent) :  
  6.     QDialog(parent)  
  7. {  
  8.     //創建一個QListWidget控件 並向其中添加列表項  
  9.     list = new QListWidget();  
  10.     list->insertItem(0, tr("文本窗口"));  
  11.     list->insertItem(1, tr("顯示窗口"));  
  12.     list->insertItem(2, tr("關於窗口"));  
  13.       
  14.     textLabel = new QLabel(tr("學習使用堆棧窗口"));  
  15.     showLabel = new QLabel(tr("僅僅是一個示例程序"));  
  16.     aboutLabel = new QLabel(tr("歡迎交流,共同學習"));  
  17.       
  18.     //創建QStackedwidget控件  
  19.     stack = new QStackedWidget();  
  20.     //將控件添加到堆棧窗口中  
  21.     stack->addWidget(textLabel);  
  22.     stack->addWidget(showLabel);  
  23.     stack->addWidget(aboutLabel);  
  24.       
  25.     //使用一個水平布局管理器對對話框進行布局  
  26.     QHBoxLayout *mainLayout = new QHBoxLayout(this);  
  27.     mainLayout->addWidget(list);  
  28.     mainLayout->addWidget(stack, 0, Qt::AlignHCenter);  
  29.     //設置mainLayout的邊框與對話框邊緣的距離  
  30.     mainLayout->setMargin(5);  
  31.     mainLayout->setSpacing(5);  
  32.     //信號與槽的連接,實現按選擇顯示窗體  
  33.     //此處堆棧窗口的index按插入的順序從0依次排序,與QListWidget的條目排序一致  
  34.     connect(list, SIGNAL(currentRowChanged(int)), stack, SLOT(setCurrentIndex(int)));  
  35.       
  36.     this->setWindowTitle(tr("堆棧窗口"));  
  37. }  


 

[cpp]  view plain copy print ?
 
  1. //main.cpp  
  2. #include <QApplication>  
  3. #include <QTextCodec>  
  4. #include "stackeddlg.h"  
  5. int main(int argc, char *argv[])  
  6. {  
  7.     QTextCodec::setCodecForTr(QTextCodec::codecForLocale());  
  8.     QApplication app(argc, argv);  
  9.     StackedDlg dlg;  
  10.     dlg.show();  
  11.     return app.exec();  
  12. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM