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();
}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部