QT 控件大小的自适应(重写resizeEvent方法)

QtEventFilter.h

#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QtEventFilter.h"
#include <QMap>
#include <QWidget>
#include <QResizeEvent>
class QtEventFilter : public QMainWindow
{
    Q_OBJECT
public:
    QtEventFilter(QWidget *parent = nullptr);
    ~QtEventFilter();
protected:
    void resizeEvent(QResizeEvent* event) override;
private:
    Ui::QtEventFilterClass ui;
    QList<QWidget*> m_objList; 
    QMap<QWidget*, QRect> m_objMap; 
    QSize m_originalSize;
};

QtEventFilter.cpp

#include "QtEventFilter.h"
QtEventFilter::QtEventFilter(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    m_objList = this->findChildren<QWidget*>();
    foreach(QWidget * widget, m_objList)
    {
        if (widget != this) 
        {
            m_objMap.insert(widget, widget->geometry());
        }
    }
    m_originalSize = this->size();
}
void QtEventFilter::resizeEvent(QResizeEvent* event)
{
    double scaleX = event->size().width() * 1.0 / m_originalSize.width();
    double scaleY = event->size().height() * 1.0 / m_originalSize.height();
    for (auto iter = m_objMap.begin(); iter != m_objMap.end(); ++iter)
    {
        QWidget* widget = iter.key();
        QRect originalGeometry = iter.value();
        QRect newGeometry(
            originalGeometry.x() * scaleX,
            originalGeometry.y() * scaleY,
            originalGeometry.width() * scaleX,
            originalGeometry.height() * scaleY
        );
        widget->setGeometry(newGeometry);
    }
    //m_originalSize = event->size();
}
QtEventFilter::~QtEventFilter()
{}

main.cpp

#include "QtEventFilter.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QtEventFilter w;
    w.show();
    return a.exec();
}
上一篇:Spring——单元测试


下一篇:python基础大杂烩