该窗口有两个窗口控件,内部控件按照自定义比例伸缩
1 主窗口相关代码
#pragma once
#include <QWidget>
class uimainwnd : public QWidget
{
Q_OBJECT
public:
uimainwnd(QWidget *parent = Q_NULLPTR);
~uimainwnd();
protected:
void resizeEvent(QResizeEvent* event) override;
private:
void initUI();
QHBoxLayout *m_hbLayoutMain;
};
#include "stdafx.h"
#include "uimainwnd.h"
#include "uititlebar.h"
#include "uicontentwnd.h"
static inline void GetScaleAndCenterPos(int baseCX, int baseCY, int windowCX,
int windowCY, int& x, int& y,
float& scale)
{
double windowAspect, baseAspect;
int newCX, newCY;
windowAspect = double(windowCX) / double(windowCY);
baseAspect = double(baseCX) / double(baseCY);
if (windowAspect > baseAspect) {
scale = float(windowCY) / float(baseCY);
newCX = int(double(windowCY) * baseAspect);
newCY = windowCY;
}
else {
scale = float(windowCX) / float(baseCX);
newCX = windowCX;
newCY = int(float(windowCX) / baseAspect);
}
x = windowCX / 2 - newCX / 2;
y = windowCY / 2 - newCY / 2;
}
static inline void GetCenterPosFromFixedScale(int baseCX, int baseCY,
int windowCX, int windowCY,
int& x, int& y, float scale)
{
x = (float(windowCX) - float(baseCX) * scale) / 2.0f;
y = (float(windowCY) - float(baseCY) * scale) / 2.0f;
}
static inline QSize GetPixelSize(QWidget* widget)
{
#ifdef SUPPORTS_FRACTIONAL_SCALING
return widget->size() * widget->devicePixelRatioF();
#else
return widget->size() * widget->devicePixelRatio();
#endif
}
uimainwnd::uimainwnd(QWidget *parent)
: QWidget(parent)
{
this->setAutoFillBackground(true);
QPalette palette(this->palette());
palette.setColor(QPalette::Background, RGB(76, 76, 76));
this->setPalette(palette);
initUI();
}
uimainwnd::~uimainwnd()
{
}
void uimainwnd::initUI()
{
setWindowTitle("固定比例窗口");
resize(650, 350);
m_hbLayoutMain = new QHBoxLayout(this);
uicontentwnd* _uicontentwnd = new uicontentwnd(this);
m_hbLayoutMain->addWidget(_uicontentwnd);
m_hbLayoutMain->setContentsMargins(0, 0, 0, 0);
setLayout(m_hbLayoutMain);
}
void uimainwnd::resizeEvent(QResizeEvent* event)
{
QSize targetSize;
targetSize = GetPixelSize(this);
int x;
int y;
float scale;
GetScaleAndCenterPos(
4,
3,
targetSize.width(),
targetSize.height(),
x,
y,
scale);
m_hbLayoutMain->setContentsMargins(x, y, x, y);
}
2 内部窗口控件相关代码
#pragma once
#include <QWidget>
class uicontentwnd : public QWidget
{
Q_OBJECT
public:
uicontentwnd(QWidget *parent = Q_NULLPTR);
~uicontentwnd();
};
#include "stdafx.h"
#include "uicontentwnd.h"
uicontentwnd::uicontentwnd(QWidget *parent)
: QWidget(parent)
{
this->setAutoFillBackground(true);
QPalette palette(this->palette());
palette.setColor(QPalette::Background, RGB(238, 238, 238));
this->setPalette(palette);
}
uicontentwnd::~uicontentwnd()
{
}