qt mouse drag the position of the picture in the scrollArea

Realize the use of qt mouse to drag the position of the picture in the scrollArea, except for the name of class A, all others can be copied and used

head File

#include <QMouseEvent>
#include <cmath>
#include <QPoint>

Add the following members to class A

	QPoint preDot;//记录鼠标移动前位置
	QPoint offset;//一次的偏移
	bool mousePress = false;//鼠标按压状态
	void mousePressEvent(QMouseEvent *event);//鼠标按键事件
	void mouseReleaseEvent(QMouseEvent *event);//鼠标放开事件
	void mouseMoveEvent(QMouseEvent *event);//鼠标移动事件

Rewrite the three event functions in the ccp file

mousePressEvent

void A::mousePressEvent(QMouseEvent *event)
{
    
    
	QRect paint = ui->scrollArea->geometry();//记录scrollArea的区域
	if (event->button() == Qt::LeftButton && paint.contains(event->pos()))//如果按的是鼠标左键且在scorllArea范围内
	{
    
    
		mousePress = true;
		this->setCursor(Qt::OpenHandCursor);//改变鼠标样式为手
		preDot = event->pos();//记录起点
	}
}

mouseReleaseEvent

void A::mouseReleaseEvent(QMouseEvent *event)
{
    
    
	if (event->button() == Qt::LeftButton)//如果松开鼠标左键
	{
    
    
		mousePress = false;
		this->setCursor(Qt::ArrowCursor);//恢复鼠标样式为箭头
	}
}

mouseMoveEvent

void A::mouseMoveEvent(QMouseEvent *event)
{
    
    
	if (mousePress)
	{
    
    
		//记录scorllArea的横纵滚动条
		QScrollBar *tmph = ui->scrollArea->horizontalScrollBar();
		QScrollBar *tmpv = ui->scrollArea->verticalScrollBar();
		//记录鼠标横纵偏移量
		offset.setX(event->x() - preDot.x());
		offset.setY(event->y() - preDot.y());

		//判断鼠标往哪边移动的,进度条就往哪边动,abs为求绝对值函数
		if (offset.x() > 0 && offset.x() > abs(offset.y()))
		{
    
    
			tmph->setValue(tmph->value() - 2);
		}
		else if (offset.x() < 0 && abs(offset.x()) > abs(offset.y()))
		{
    
    
			tmph->setValue(tmph->value() + 2);
		}
		else if (offset.y() > 0 && offset.y() > abs(offset.x()))
		{
    
    
			tmpv->setValue(tmpv->value() - 2);
		}
		else if (offset.y() < 0 && abs(offset.y()) > abs(offset.x()))
		{
    
    
			tmpv->setValue(tmpv->value() + 2);
		}
	}
}

Guess you like

Origin blog.csdn.net/Fengfgg/article/details/113373554