Qt中ui页面交互切换

在Qt中实现UI页面之间的交互切换通常需要使用堆栈窗口(QStackedWidget)或选项卡窗口(QTabWidget)这样的控件。下面是一个简单的示例代码,演示了如何在Qt中实现UI页面的交互切换:

假设我们有两个页面,一个是Page1,另一个是Page2,我们通过点击按钮在这两个页面之间进行切换。

首先,在Qt Designer中设计UI界面,添加两个页面和一个按钮,分别为page1.ui和page2.ui。

page1.ui包含一个按钮btn_switch,点击该按钮切换到page2;page2.ui包含一个按钮btn_switch,点击该按钮切换到page1。

然后在Qt中实现页面的交互切换逻辑:

```cpp

// 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 switchToPage1();

void switchToPage2();

private:

QStackedWidget *stackedWidget;

};

#endif // MAINWINDOW_H

```

```cpp

// mainwindow.cpp

#include "mainwindow.h"

#include <QStackedWidget>

#include <QFile>

#include <QVBoxLayout>

#include <QPushButton>

MainWindow::MainWindow(QWidget *parent)

: QMainWindow(parent)

{

stackedWidget = new QStackedWidget(this);

// Load page1.ui

QWidget *page1Widget = new QWidget;

QVBoxLayout *page1Layout = new QVBoxLayout;

QPushButton *btn_switch1 = new QPushButton("Switch to Page 2");

page1Layout->addWidget(btn_switch1);

page1Widget->setLayout(page1Layout);

stackedWidget->addWidget(page1Widget);

// Load page2.ui

QWidget *page2Widget = new QWidget;

QVBoxLayout *page2Layout = new QVBoxLayout;

QPushButton *btn_switch2 = new QPushButton("Switch to Page 1");

page2Layout->addWidget(btn_switch2);

page2Widget->setLayout(page2Layout);

stackedWidget->addWidget(page2Widget);

connect(btn_switch1, &QPushButton::clicked, this, &MainWindow::switchToPage2);

connect(btn_switch2, &QPushButton::clicked, this, &MainWindow::switchToPage1);

setCentralWidget(stackedWidget);

}

MainWindow::~MainWindow()

{

}

void MainWindow::switchToPage1()

{

stackedWidget->setCurrentIndex(0);

}

void MainWindow::switchToPage2()

{

stackedWidget->setCurrentIndex(1);

}

```

在MainWindow类的构造函数中,我们创建了一个QStackedWidget,并在其中加载了两个页面。通过connect函数连接按钮的clicked信号和自定义的槽函数,实现页面之间的切换。通过调用setCurrentIndex方法可以切换显示的页面。

这样,当用户点击按钮时,就可以在两个页面之间进行交互切换了。希望这个示例可以帮助你实现在Qt中实现UI页面的交互切换。

相关推荐
aramae1 小时前
模拟实现strcmp()(C语言)
c语言·开发语言·后端
泡海椒2 小时前
PDF 表格样式优化:jquick-pdf 边框、圆角、背景色
java·开发语言·pdf
Beyond_System|系统之外3 小时前
【学编程】Python基础编程题100道(21-60)
开发语言·python·算法
景熙55233 小时前
15.Java 8 Stream 流入门到实战
java·开发语言·数据结构
Bruce_Liuxiaowei6 小时前
Python 实例赋值遮蔽类属性:一个从不报错的静默陷阱
开发语言·python·语法糖
aramae7 小时前
MySQL内置函数(7)
开发语言·笔记·后端·mysql·其他
码行山野赴时序归途10 小时前
链表家族收官篇:循环链表
c语言·开发语言·数据结构·链表
景熙552310 小时前
单体项目编写思路和落地形式
java·开发语言
计算机毕设定制辅导-无忧学长11 小时前
《基于SpringBoot的未成年人健康知识科普平台的设计与实现》
java·开发语言·vue.js·spring boot·未成年人健康知识科普平台
Ivanqhz11 小时前
Ping-Pong 双缓冲
开发语言·人工智能·python·深度学习·mlir