使用qt实现窗口切换
要实现窗口切换,需要使用Qt的窗口管理类QStackedWidget。QStackedWidget提供了一种容器,可以在其中堆叠多个窗口小部件。只有当前窗口小部件是可见的,其他窗口小部件则被隐藏。
以下是实现窗口切换的步骤:
-
创建一个QStackedWidget对象,作为主窗口。
-
创建多个QWidget对象,每个对象代表一个窗口。
-
使用addWidget()方法将所有QWidget对象添加到QStackedWidget中。
-
使用setCurrentIndex()方法将默认显示的窗口设置为0(第一个窗口)。
-
在需要切换窗口的时候,使用setCurrentIndex()方法将要显示的窗口的索引设置为当前索引。
下面是一个简单的例子:
mainwindow.h文件:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStackedWidget>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_button1_clicked();
void on_button2_clicked();
void on_button3_clicked();
private:
QStackedWidget *stackedWidget;
QWidget *page1;
QWidget *page2;
QWidget *page3;
};
#endif // MAINWINDOW_H
mainwindow.cpp文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
stackedWidget = new QStackedWidget(this);
page1 = new QWidget;
page2 = new QWidget;
page3 = new QWidget;
// 添加页面
stackedWidget->addWidget(page1);
stackedWidget->addWidget(page2);
stackedWidget->addWidget(page3);
// 第一页
QPushButton *button1 = new QPushButton("Go to page 2", page1);
connect(button1, SIGNAL(clicked()), this, SLOT(on_button1_clicked()));
// 第二页
QPushButton *button2 = new QPushButton("Go to page 3", page2);
connect(button2, SIGNAL(clicked()), this, SLOT(on_button2_clicked()));
// 第三页
QPushButton *button3 = new QPushButton("Go to page 1", page3);
connect(button3, SIGNAL(clicked()), this, SLOT(on_button3_clicked()));
// 设置布局
QVBoxLayout *layout1 = new QVBoxLayout(page1);
layout1->addWidget(button1);
QVBoxLayout *layout2 = new QVBoxLayout(page2);
layout2->addWidget(button2);
QVBoxLayout *layout3 = new QVBoxLayout(page3);
layout3->addWidget(button3);
// 设置默认页
stackedWidget->setCurrentIndex(0);
setCentralWidget(stackedWidget);
}
MainWindow::~MainWindow()
{
}
void MainWindow::on_button1_clicked()
{
stackedWidget->setCurrentIndex(1);
}
void MainWindow::on_button2_clicked()
{
stackedWidget->setCurrentIndex(2);
}
void MainWindow::on_button3_clicked()
{
stackedWidget->setCurrentIndex(0);
}
在这个例子中,我们创建了三个QWidget对象,每个对象代表一个窗口。我们使用addWidget()方法将这三个QWidget对象添加到QStackedWidget中。然后,我们在每个QWidget对象中添加了一个QPushButton对象,用于切换到其他窗口。
在MainWindow类中,我们实现了on_button1_clicked()、on_button2_clicked()和on_button3_clicked()槽函数,用于切换到其他窗口。在构造函数中,我们将QStackedWidget设置为主窗口的中央窗口。最后,我们使用setCurrentIndex()方法将默认显示的窗口设置为第一个窗口。
原文地址: https://www.cveoy.top/t/topic/dvMq 著作权归作者所有。请勿转载和采集!