QT QGraphicsView 在鼠標點擊處進行放大縮小

一、前段時間在用QGraphicsView對圖元進行放大縮小時,發現圖形總是越來越跑偏,無法像地圖中那樣,點擊哪裏就能放大哪個地方。
如下所示:此時放大縮小的焦點並不在鼠標位置最初的效果
方法,使用QGraphicsView類的設置屬性函數.在構造函數中增加下面兩個函數即可。

setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
setResizeAnchor(QGraphicsView::AnchorUnderMouse);

此時以鼠標爲中心的效果就出來了:
改進後的效果
完整代碼:

MyGraphicsView::MyGraphicsView()
{
	setDragMode(QGraphicsView::NoDrag);//(QGraphicsView::RubberBandDrag);//QGraphicsView::ScrollHandDrag
	scale_m = 1;//圖形原始比例
	setStyleSheet("padding: 0px; border: 0px;");//無邊框
	setMouseTracking(true);//跟蹤鼠標位置
	setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隱藏水平條
	setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隱藏豎條
	setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
	setResizeAnchor(QGraphicsView::AnchorUnderMouse);
	
}
void MyGraphicsView::wheelEvent ( QWheelEvent * event )
{
	if (event->modifiers() == Qt::CTRL)
	{//按住ctrl鍵 可以放大縮小
		if((event->delta() > 0)&&(scale_m >= 50))//最大放大到原始圖像的50倍
		{
			return;
		}
		else if((event->delta() < 0)&&(scale_m <= 0.01))//圖像縮小到自適應大小之後就不繼續縮小
		{
			return;//重置圖片大小和位置,使之自適應控件窗口大小
		}
		else
		{
			// 當前放縮倍數;
			qreal scaleFactor = this->matrix().m11();
			scale_m = scaleFactor;
			
			int wheelDeltaValue = event->delta();
			// 向上滾動,放大;
			if (wheelDeltaValue > 0)
			{
				this->scale(1.2, 1.2);
			}
			else
			{// 向下滾動,縮小;
				this->scale(1.0 / 1.2, 1.0 / 1.2);
			}
			update();
		}
	}	
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章