QT widget宽高比

1、首先想到的是---重载resizeEvennt

void resizeEvent(QResizeEvent * event)
{
	//当前宽高
	int nWidth = event->size().width();
	int nHeight = event->size().height();
	//太宽了
	if (nWidth * 9 > nHeight * 16)
	{
		nWidth = nHeight * 16.0 /  9.0;
	}
	else //太高了
	{
		nHeight = nWidth * 9 / 16.0;
	}

        //需要注意的是 这里不能调用resize, reseize会重新resizeEvent 死循环 

	setFixedSize(nWidth, nHeight);
}

此方法设置了SixedSize 导致宽高固定,当这个widet在别的布局中就不OK了

2、重写鼠标事件

#include "screenwidget.h"
#include "ui_screenwidget.h"

screenWidget::screenWidget(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::screenWidget)
	, m_bMousePress(false)
	, m_shape(Qt::ArrowCursor)
{
	m_dAspectRatio = 16.0 / 9;
	ui->setupUi(this);
	//去掉QWidget的Frame
	setWindowFlags(Qt::FramelessWindowHint);
	//自定义鼠标事件
	//setMouseTracking(true);
}

screenWidget::~screenWidget()
{
	delete ui;
}
//提供外部设置宽高比例
void screenWidget::setAspectRatio(double dAspectRatio)
{
	if (dAspectRatio > 0)
	{
		m_dAspectRatio = dAspectRatio;
	}
}

//自定义鼠标状态
void screenWidget::mouseMoveEvent(QMouseEvent * event)
{       //当鼠标按下 且状态是拖动状态 则不需要相应
	if (!m_bMousePress)
	{
		QRect rect = this->rect();
                 //5像素内变化鼠标状态
		if (rect.x() < event->pos().x() && (event->pos().x() < rect.x() + 5))
		{
			m_shape = Qt::SizeHorCursor;
		}
		else if (rect.y() < event->pos().y() && (event->pos().y() < rect.y() + 5))
		{
			m_shape = Qt::SizeVerCursor;
		}
		else
		{
			m_shape = Qt::ArrowCursor;
		}
		QApplication::setOverrideCursor(QCursor(m_shape));
	}
}
//在鼠标按下时候去 记录鼠标按下的位置并  记录下鼠标在拉伸状态下变化
void screenWidget::mousePressEvent(QMouseEvent * event)
{
	if (event->button() == Qt::LeftButton && m_shape != Qt::ArrowCursor)
	{
		m_pt = event->globalPos();
		m_bMousePress = true;
	}
}
//当鼠标松开时候 需要更新2个鼠标位置设置widget重新的大小
void screenWidget::mouseReleaseEvent(QMouseEvent * event)
{
	if (m_shape != Qt::ArrowCursor && m_bMousePress)
	{
		int nWidth;
		int nHeight;
		QPoint pt = event->globalPos();
		QRect rect = this->rect();
		//水平的拖动
		if (Qt::SizeHorCursor == m_shape)
		{
			//取绝对值计算是 支持拉伸和回缩
			int nX = pt.x() - m_pt.x();//拖动
			nWidth = abs(rect.width() - nX);
			nHeight = nWidth / m_dAspectRatio;
		}
		else
		{
			int nY = pt.y() - m_pt.y();
			nHeight = abs(rect.height() - nY);
			nWidth = nHeight * m_dAspectRatio;
		}
		setFixedSize(nWidth, nHeight);

		m_shape = Qt::ArrowCursor;
		QApplication::setOverrideCursor(QCursor(m_shape));
		m_bMousePress = false;
	}
}

此方法解决了拖动的效果,但是当此widget被加入其它布局中时候,鼠标拖动的效果会能改动它的大小(弊端)

3、过滤器

你可能感兴趣的:(QT widget宽高比)