Qt之QStackedWidget多界面切換

簡述

QStackedWidget繼承自QFrame。

QStackedWidget類提供了多頁面切換的佈局,一次只能看到一個界面。

QStackedWidget可用於創建類似於QTabWidget提供的用戶界面。

 

 

使用

一個QStackedWidget可以用一些子頁面進行填充。

效果

這裏寫圖片描述

源碼

QPushButton *pButton = new QPushButton(this);
QLabel *pFirstPage= new QLabel(this);
QLabel *pSecondPage = new QLabel(this);
QLabel *pThirdPage = new QLabel(this);
m_pStackedWidget = new QStackedWidget(this);

pButton->setText(QStringLiteral("點擊切換"));
pFirstPage->setText(QStringLiteral("一去丶二三裏"));
pSecondPage->setText(QStringLiteral("青春不老,奮鬥不止!"));
pThirdPage->setText(QStringLiteral("純正開源之美,有趣、好玩、靠譜。。。"));

// 添加頁面(用於切換)
m_pStackedWidget->addWidget(pFirstPage);
m_pStackedWidget->addWidget(pSecondPage);
m_pStackedWidget->addWidget(pThirdPage);

QVBoxLayout *pLayout = new QVBoxLayout();
pLayout->addWidget(pButton, 0, Qt::AlignLeft | Qt::AlignVCenter);
pLayout->addWidget(m_pStackedWidget);
pLayout->setSpacing(10);
pLayout->setContentsMargins(10, 10, 10, 10);
setLayout(pLayout);

// 連接切換按鈕信號與槽
connect(pButton, &QPushButton::clicked, this, &MainWindow::switchPage);

// 切換頁面
void MainWindow::switchPage()
{
    int nCount = m_pStackedWidget->count();
    int nIndex = m_pStackedWidget->currentIndex();

    // 獲取下一個需要顯示的頁面索引
    ++nIndex;

    // 當需要顯示的頁面索引大於等於總頁面時,切換至首頁
    if (nIndex >= nCount)
        nIndex = 0;

    m_pStackedWidget->setCurrentIndex(nIndex);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

接口

  • int addWidget(QWidget * widget)

    添加頁面,並返回頁面對應的索引

  • int count() const

    獲取頁面數量

  • int currentIndex() const

    獲取當前頁面的索引

  • QWidget * currentWidget() const

    獲取當前頁面

  • int indexOf(QWidget * widget) const

    獲取QWidget頁面所對應的索引

  • int insertWidget(int index, QWidget * widget)

    在索引index位置添加頁面

  • void removeWidget(QWidget * widget)

    移除QWidget頁面,並沒有被刪除,只是從佈局中移動,從而被隱藏。

  • QWidget * widget(int index) const

    獲取索引index所對應的頁面

信號

  • void currentChanged(int index)

    當前頁面發生變化時候發射,index爲新的索引值

  • void widgetRemoved(int index)

    頁面被移除時候發射,index爲頁面對應的索引值

共有槽函數

  • void setCurrentIndex(int index)

    設置索引index所在的頁面爲當前頁面

  • void setCurrentWidget(QWidget * widget)

    設置QWidget頁面爲當前頁面

總結

一般情況,常用的兩種方式:

 


  • 根據currentWidget()來判斷當前頁面,然後通過setCurrentWidget()來設置需要顯示的頁面。

  • 根據currentIndex()來判斷當前頁面索引,然後通過setCurrentIndex()來設置需要顯示的頁面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章