在vscode里用c++代码两个选择的QRaioButton按钮用同一个布局,显示相同布局的不同的内容
时间: 2023-12-10 19:39:47 浏览: 31
可以通过使用QStackedWidget控件来实现在同一布局中显示不同内容。具体实现步骤如下:
1. 在布局中添加一个QStackedWidget控件。
2. 在QStackedWidget控件中添加两个QWidget子控件,分别用于显示两个不同的内容。
3. 在布局中添加两个QRadioButton控件,用于切换显示的内容。
4. 通过连接QRadioButton的信号和QStackedWidget的槽函数,实现当选择不同的QRadioButton时,显示对应的QWidget子控件。
以下是示例代码:
```cpp
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
QVBoxLayout *layout = new QVBoxLayout(&window);
QStackedWidget *stackedWidget = new QStackedWidget(&window);
// 添加两个QWidget子控件
QWidget *widget1 = new QWidget();
QLabel *label1 = new QLabel("Content 1", widget1);
label1->setAlignment(Qt::AlignCenter);
QVBoxLayout *layout1 = new QVBoxLayout(widget1);
layout1->addWidget(label1);
QWidget *widget2 = new QWidget();
QLabel *label2 = new QLabel("Content 2", widget2);
label2->setAlignment(Qt::AlignCenter);
QVBoxLayout *layout2 = new QVBoxLayout(widget2);
layout2->addWidget(label2);
stackedWidget->addWidget(widget1);
stackedWidget->addWidget(widget2);
// 添加两个QRadioButton控件
QRadioButton *button1 = new QRadioButton("Button 1", &window);
QRadioButton *button2 = new QRadioButton("Button 2", &window);
// 连接QRadioButton的信号和QStackedWidget的槽函数
QObject::connect(button1, &QRadioButton::clicked, [=]() {
stackedWidget->setCurrentIndex(0);
});
QObject::connect(button2, &QRadioButton::clicked, [=]() {
stackedWidget->setCurrentIndex(1);
});
// 将控件添加到布局中
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(stackedWidget);
window.show();
return app.exec();
}
```
运行程序,选择不同的QRadioButton即可看到不同的内容在同一布局中显示。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)