编写Qt的QStackWidget示例用法代码
时间: 2023-03-31 22:00:54 浏览: 102
QStackedWidget是一个用于管理多个窗口的小部件,它可以让用户在这些窗口之间进行切换。以下是一个简单的示例代码:
```c++
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStackedWidget stackedWidget;
QWidget *page1 = new QWidget;
QLabel *label1 = new QLabel("This is page 1");
QVBoxLayout *layout1 = new QVBoxLayout(page1);
layout1->addWidget(label1);
QWidget *page2 = new QWidget;
QLabel *label2 = new QLabel("This is page 2");
QVBoxLayout *layout2 = new QVBoxLayout(page2);
layout2->addWidget(label2);
stackedWidget.addWidget(page1);
stackedWidget.addWidget(page2);
QPushButton *button1 = new QPushButton("Show page 1");
QObject::connect(button1, &QPushButton::clicked, [&](){
stackedWidget.setCurrentWidget(page1);
});
QPushButton *button2 = new QPushButton("Show page 2");
QObject::connect(button2, &QPushButton::clicked, [&](){
stackedWidget.setCurrentWidget(page2);
});
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(button1);
layout->addWidget(button2);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(&stackedWidget);
mainLayout->addLayout(layout);
QWidget window;
window.setLayout(mainLayout);
window.show();
return app.exec();
}
```
阅读全文