Qt编程之通过鼠标滚轮事件缩放QGraphicsView里面的Item

首先自己subclass QGraphicsView的一个类,叫DiagramView,然后重新实现它的滚轮事件函数,然后发送一个缩放信号:

 1 oid DiagramView::wheelEvent(QWheelEvent * event){
 2 
 3     if (event->delta() > 0)
 4     {
 5         emit mouseWheelZoom(true);
 6     }
 7     else
 8     {
 9         emit mouseWheelZoom(false);
10     }
11 
12 }
View Code

然后用connect把这个信号连接到要实现的槽函数上(ScaleFactor初始化为30):

 1 void TopologyEditor::Zoom(bool zoom){
 2 
 3     
 4 
 5     
 6 
 7     if (zoom && scaleFactor >= 0)
 8     {
 9         
10         scaleFactor += 10;
11         QMatrix old_matrix;
12         old_matrix = view->matrix();
13         view->resetMatrix();
14         view->translate(old_matrix.dx(), old_matrix.dy());
15         view->scale(scaleFactor/100.0, scaleFactor/100.0);
16     }
17     else if (!zoom && scaleFactor >= 0)
18     {
19         scaleFactor -= 10;
20         QMatrix old_matrix;
21         old_matrix = view->matrix();
22         view->resetMatrix();
23         view->translate(old_matrix.dx(), old_matrix.dy());
24         
25         view->scale( scaleFactor/100.0,  scaleFactor/100.0);
26 
27     }
28 
29     else if (scaleFactor < 0){
30     
31         scaleFactor = 0.0;
32     }
33 
34 }
View Code

references:

http://stackoverflow.com/questions/19113532/qgraphicsview-zooming-in-and-out-under-mouse-position-using-mouse-wheel

http://www.qtcentre.org/threads/52603-Zoom-effect-by-mouse-Wheel-in-QGraphicsview

原文地址:https://www.cnblogs.com/foohack/p/4536025.html