一、前段時間在用QGraphicsView對圖元進行放大縮小時,發現圖形總是越來越跑偏,無法像地圖中那樣,點擊哪里就能放大哪個地方。
如下所示:此時放大縮小的焦點並不在鼠標位置

方法,使用QGraphicsView類的設置屬性函數.在構造函數中增加下面兩個函數即可。
ui.View_ImageOpro->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
ui.View_ImageOpro->setResizeAnchor(QGraphicsView::AnchorUnderMouse);
此時以鼠標為中心的效果就出來了:

完整代碼:
MyGraphicsView::MyGraphicsView() {
//設置ui控件屬性 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(); } } }
