效果:
上下收缩、折叠面板,类似QQ好友列表那种。原理就是在一个布局中,通过button来实现一个独立widget的visible/disable
实现:
1.分组按钮
#ifndef EXPANDPANEL_H
#define EXPANDPANEL_H
#include <QWidget>
class QLabel;
class ExpandPanel : public QWidget
{
Q_OBJECT
public:
ExpandPanel(QWidget* parent=nullptr);
void setTitle(const QString& title);
signals:
void statuChanged(bool expand);
protected:
void mousePressEvent(QMouseEvent *event);
private:
QLabel* logo;
QLabel* title;
QLabel* icon;
bool mExpand = true;
};
#endif // EXPANDPANEL_H
#include "expandpanel.h"
#include "parse/parsework.h"
#include <QDebug>
#include <QLabel>
#include <QVariant>
#include <QHBoxLayout>
#include <QStyle>
ExpandPanel::ExpandPanel(QWidget *parent)
:QWidget(parent)
{
logo = new QLabel;
logo->setObjectName("logo");
title = new QLabel;
title->setObjectName("title");
icon = new QLabel;
icon->setObjectName("icon");
icon->setProperty("expand", true);
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(logo);
layout->addWidget(title);
layout->addStretch(1);
layout->addWidget(icon);
layout->setContentsMargins(0,0,0,0);
ParseWork::Instance().dynamicUpdateStyleSheet(this,
":/qss/src/qss/expandpanel.qss");
}
void ExpandPanel::setTitle(const QString &name)
{
title->setText(name);
}
void ExpandPanel::mousePressEvent(QMouseEvent *event)
{
QWidget::mousePressEvent(event);
mExpand = !mExpand;
emit statuChanged(mExpand);
icon->setProperty("expand", mExpand);
ParseWork::Instance().dynamicUpdateStyleSheet(this,
":/qss/src/qss/expandpanel.qss");
}
2.使用
在mainwindow中创建两部分,左边是折叠面板,右侧是一个qtabwidget(用不到则删掉)
void MainWindow::createFrame()
{
mFuncPanel = new QWidget;
mFuncVLayout = new QVBoxLayout;
mFuncPanel->setMinimumWidth(220);
mFuncPanel->setLayout(mFuncVLayout);
mFuncVLayout->setSpacing(15);
mFuncVLayout->setContentsMargins(0,0,0,0);
mLogPanel = new QTabWidget;
mLogPanel->setTabsClosable(true);
mLogPanel->setElideMode(Qt::ElideLeft);
QSplitter* spliter = new QSplitter;
spliter->setOrientation(Qt::Horizontal);
spliter->addWidget(mFuncPanel);
spliter->addWidget(mLogPanel);
spliter->setStretchFactor(1, 1);
spliter->setChildrenCollapsible(false);//very importance, not to hide child duruing moving
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(spliter);
}
void MainWindow::initLocalFilePanel()
{
mLocalFilePl = new ExpandPanel;
mLocalFilePl->setTitle(tr("LocalFile"));
LocalFile* file = new LocalFile;
mFuncVLayout->addWidget(mLocalFilePl);
mFuncVLayout->addWidget(file);
mFuncVLayout->addStretch(1);
connect(mLocalFilePl, &ExpandPanel::statuChanged, file, &LocalFile::setVisible);
}