思路:来自一个qt交流群的讨论。在下拉窗口上面的抬头栏右边加上一个图标,每次点击到这个图标,就触发展开\收缩窗口。
源代码:
#include "ExpandableLbl.h"
#include <QPixmap>
#include <QHBoxLayout>
#include <QEvent>
ExpandableLbl::ExpandableLbl(QString qstrTitle, QString qstrPix, std::function<void (void)> const & pFunc, QWidget *parent) : QWidget(parent)
{
setWindowFlags(Qt::FramelessWindowHint);
QHBoxLayout * pHBLayout = new QHBoxLayout;
pHBLayout->addWidget(new QLabel(qstrTitle));
m_pLbl = new QLabel;
QPixmap pix(qstrPix);
pix = pix.scaled(15,15);
m_pLbl->setPixmap(pix);
pHBLayout->addStretch();
pHBLayout->addWidget(m_pLbl);
setFixedHeight(50);
setLayout(pHBLayout);
m_pLbl->installEventFilter(this);
m_pFoldFunc = pFunc;
}
bool ExpandableLbl::eventFilter(QObject *watched, QEvent *event)
{
if(watched == m_pLbl)
{
if(event->type() == QEvent::MouseButtonRelease)
{
//展开或者收起
m_pFoldFunc();
return true;//不再向上传播
}
}
return QWidget::eventFilter(watched, event);
}
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QScrollArea>
#include <QVBoxLayout>
#include <QPushButton>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QScrollArea * pScrollArea = new QScrollArea;
QWidget * pWgt = new QWidget;
pWgt->setStyleSheet("background-color:red;");
QVBoxLayout * pVLayout = new QVBoxLayout;
QWidget * pWgtFoldable = new QWidget;
pWgtFoldable->setFixedHeight(500);
pWgtFoldable->setStyleSheet("background-color:green;");
QPushButton * pBtn = new QPushButton("qwertyui");
ExpandableLbl * plbl = new ExpandableLbl(QString::fromWCharArray(L"可伸缩"), QString("arrow2.png"), [pWgtFoldable](){
pWgtFoldable->setVisible(!pWgtFoldable->isVisible());
});
pVLayout->addWidget(plbl);
pVLayout->addWidget(pBtn);
pVLayout->addWidget(pWgtFoldable);
pVLayout->addWidget(new QPushButton(QString("12345678")));
pVLayout->addStretch();
pWgt->setLayout(pVLayout);
pScrollArea->setWidget(pWgt);
pScrollArea->setWidgetResizable(true);
QPushButton * pWgtBottom = new QPushButton("bottom");
ui->verticalLayout->addWidget(pScrollArea);
ui->verticalLayout->addWidget(pWgtBottom);
setFixedHeight(800);
}
MainWindow::~MainWindow()
{
delete ui;
}
效果:
展开:
收缩: