qt中stackedwidget按钮切换widget
时间: 2023-09-10 22:10:44 浏览: 237
你可以将QPushButton的clicked信号连接到QStackedWidget的setCurrentIndex槽上,以实现按钮切换widget的功能。示例代码如下:
```
// 创建QStackedWidget对象和QPushButton对象
QStackedWidget *stackedWidget = new QStackedWidget(this);
QPushButton *button1 = new QPushButton("Widget 1", this);
QPushButton *button2 = new QPushButton("Widget 2", this);
// 添加两个widget到QStackedWidget中
QWidget *widget1 = new QWidget(this);
QWidget *widget2 = new QWidget(this);
stackedWidget->addWidget(widget1);
stackedWidget->addWidget(widget2);
// 将QPushButton的clicked信号连接到QStackedWidget的setCurrentIndex槽上
connect(button1, &QPushButton::clicked, stackedWidget, [=]() {
stackedWidget->setCurrentIndex(0);
});
connect(button2, &QPushButton::clicked, stackedWidget, [=]() {
stackedWidget->setCurrentIndex(1);
});
// 创建布局,并将QPushButton添加到布局中
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(stackedWidget);
// 设置初始显示的widget
stackedWidget->setCurrentIndex(0);
```
阅读全文