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();
}
原文地址:https://blog.csdn.net/qq_49595983/article/details/143780006
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!