程序员人生 网站导航

Qt之QStackedLayout

栏目:综合技术时间:2016-06-22 08:16:58

简述

QStackedLayout继承自QLayout。

QStackedLayout类提供了多页面切换的布局,1次只能看到1个界面。

QStackedLayout可用于创建类似于QTabWidget提供的用户界面。也有建立在QStackedLayout之上的便利类QStackedWidget。

  • 简述
  • 使用
    • 效果
    • 源码
  • 接口
  • 总结

使用

1个QStackedLayout可以用1些子页面进行填充。

效果

这里写图片描述

源码

QPushButton *pButton = new QPushButton(this); QLabel *pFirstPage= new QLabel(this); QLabel *pSecondPage = new QLabel(this); QLabel *pThirdPage = new QLabel(this); m_pStackedLayout = new QStackedLayout(); pButton->setText(QStringLiteral("点击切换")); pFirstPage->setText(QStringLiteral("1去丶23里")); pSecondPage->setText(QStringLiteral("青春不老,奋斗不止!")); pThirdPage->setText(QStringLiteral("纯粹开源之美,有趣、好玩、靠谱。。。")); // 添加页面(用于切换) m_pStackedLayout->addWidget(pFirstPage); m_pStackedLayout->addWidget(pSecondPage); m_pStackedLayout->addWidget(pThirdPage); QVBoxLayout *pLayout = new QVBoxLayout(); pLayout->addWidget(pButton, 0, Qt::AlignLeft | Qt::AlignVCenter); pLayout->addLayout(m_pStackedLayout); pLayout->setSpacing(10); pLayout->setContentsMargins(10, 10, 10, 10); setLayout(pLayout); // 连接切换按钮信号与槽 connect(pButton, &QPushButton::clicked, this, &MainWindow::switchPage); // 切换页面 void MainWindow::switchPage() { int nCount = m_pStackedLayout->count(); int nIndex = m_pStackedLayout->currentIndex(); // 获得下1个需要显示的页面索引 ++nIndex; // 当需要显示的页面索引大于等于总页面时,切换至首页 if (nIndex >= nCount) nIndex = 0; m_pStackedLayout->setCurrentIndex(nIndex); }

接口

  • int addWidget(QWidget * widget)

    添加页面,并返回页面对应的索引

  • int currentIndex() const

    获得当前页面的索引

  • QWidget * currentWidget() const

    获得当前页面

  • int insertWidget(int index, QWidget * widget)

    在索引index位置添加页面

  • void setStackingMode(StackingMode stackingMode)

    设置显示模式,StackingMode有两个值,1个是StackOne(默许-显示1个页面),1个是StackAll(显示所有页面),1般不使用。

  • QWidget * widget(int index) const

    获得索引index所对应的页面

总结

1般情况,经常使用的两种方式:

  • 根据currentWidget()来判断当前页面,然后通过setCurrentWidget()来设置需要显示的页面。

  • 根据currentIndex()来判断当前页面索引,然后通过setCurrentIndex()来设置需要显示的页面。

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐