qt页面跳转
时间: 2023-07-13 12:04:57 浏览: 83
在Qt中,页面跳转通常是通过使用StackedWidget和QPushButton来实现的。StackedWidget是一个可以包含多个页面的小部件,每个页面都是一个QWidget。QPushButton用于触发页面切换。
以下是一个简单的示例代码,演示如何在Qt中实现页面跳转:
```cpp
#include <QApplication>
#include <QPushButton>
#include <QStackedWidget>
#include <QWidget>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
// 创建两个QWidget作为页面
QWidget *page1 = new QWidget();
QWidget *page2 = new QWidget();
// 创建一个StackedWidget并添加页面
QStackedWidget *stackedWidget = new QStackedWidget();
stackedWidget->addWidget(page1);
stackedWidget->addWidget(page2);
// 创建两个QPushButton用于切换页面
QPushButton *button1 = new QPushButton("Page 1");
QPushButton *button2 = new QPushButton("Page 2");
// 连接按钮单击信号和槽函数,实现页面切换
QObject::connect(button1, &QPushButton::clicked,
[=]() { stackedWidget->setCurrentIndex(0); });
QObject::connect(button2, &QPushButton::clicked,
[=]() { stackedWidget->setCurrentIndex(1); });
// 创建一个父QWidget并设置布局
QWidget *window = new QWidget();
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(stackedWidget);
window->setLayout(layout);
window->show();
return a.exec();
}
```
在这个示例中,我们创建了两个QWidget作为页面,然后将它们添加到StackedWidget中。我们还创建了两个QPushButton用于切换页面,然后将它们添加到一个垂直布局中。最后,我们将StackedWidget和按钮布局添加到一个父QWidget中,并显示它。
当我们单击按钮时,对应的页面将显示在StackedWidget中。我们使用StackedWidget的setCurrentIndex函数来设置当前页面的索引。在这个示例中,页面1的索引是0,页面2的索引是1。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)