1、实现效果和UI设计界面
2、工程目录
3、mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QToolButton>
#include <QPushButton>
#include <vector>
using namespace std;QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private:Ui::MainWindow *ui;/*** @brief 初始化 UI*/void initUI();// 要折叠的内容vector<QWidget*> widgetBodys;// 要用到的 toolButtonvector<QToolButton*> toolButtons;// 折叠按钮 pushButtonvector<QPushButton*> pushButtons;private slots:// 点击打开和关闭抽屉按钮void on_btns_clicked();
};
#endif // MAINWINDOW_H
4、mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);// 初始化 UIinitUI();
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::initUI()
{// 要折叠的内容widgetBodys.push_back(ui->widgetOneBody);widgetBodys.push_back(ui->widgetTwoBody);widgetBodys.push_back(ui->widgetThreeBody);// 要用到的 toolButtontoolButtons.push_back(ui->toolButtonOne);toolButtons.push_back(ui->toolButtonTwo);toolButtons.push_back(ui->toolButtonThree);// 折叠按钮 pushButtonpushButtons.push_back(ui->pushButtonOne);pushButtons.push_back(ui->pushButtonTwo);pushButtons.push_back(ui->pushButtonThree);for(size_t i = 0;i < widgetBodys.size();++i){// 设置 ToolButton 的样式toolButtons[i]->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);toolButtons[i]->setIcon(QIcon(QPixmap(":/res/functions.png")));toolButtons[i]->setText(QString::fromLocal8Bit("常用功能"));// 设置抽屉按钮的样式,抽屉默认折叠pushButtons[i]->setIcon(QIcon(QPixmap(":/res/close.png")));// 设置抽屉默认折叠,一定记得在 UI 设计界面将 layoutTopMargin 和 layoutBottomMargin 设置为0widgetBodys[i]->hide();// 方便后面点击按钮时获取点击的哪个按钮pushButtons[i]->setProperty("index",i);connect(pushButtons[i],&QPushButton::clicked,this,&MainWindow::on_btns_clicked);}
}void MainWindow::on_btns_clicked()
{// 获取点击的按钮QPushButton *pushButton = qobject_cast<QPushButton*>(sender());if(pushButton){int index = pushButton->property("index").toInt();if(widgetBodys[index]->isVisible()){// 当前抽屉是展开的// 关闭抽屉widgetBodys[index]->hide();// 按钮变为关闭状态pushButton->setIcon(QIcon(QPixmap(":/res/close.png")));}else{// 当前抽屉是关闭的// 打开抽屉widgetBodys[index]->show();// 按钮变为打开状态pushButton->setIcon(QIcon(QPixmap(":/res/open.png")));}}
}