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

接口

  • 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()来设置需要显示的页面。

原博客地址:http://blog.csdn.net/liang19890820/article/details/51614346
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值