title: QGraphicsView Zooming in and out under mouse position using mouse wheel
body: <p>I have an application with a <code>QGraphicsView</code> window in the middle of the screen. I want to be able to zoom in and out using a mouse wheel scroll. </p>
  
  <p>Currently I have re-implemented <code>QGraphicsView</code> and overriden the mouse scroll function so that it doesn't scroll the image (like it does by default).  </p>
  
  <pre><code>void MyQGraphicsView::wheelEvent(QWheelEvent *event)
  {
      if(event-&gt;delta() &gt; 0)
      {
          emit mouseWheelZoom(true);
      }
      else
      {
          emit mouseWheelZoom(false);
      }
  }
  </code></pre>
  
  <p>so when I scroll, I'm emitting a signal true if mouse wheel forward false if mouse wheel back.</p>
  
  <p>I have then connected this signal to a slot (zoom function <em>see below</em>) in the class that handles my GUI stuff. Now basically I think my zoom function just isn't the best way to do it at all I have seen some examples of people using the overriden wheelevent function to set scales but I couldn't really find a complete answer.</p>
  
  <p>So instead I have done this but it's not perfect by any means so I'm looking for this to be tweaked a bit or for a working example using scale in the wheel event function.</p>
  
  <p>I initialize <code>m_zoom_level</code> to <code>0</code> in the constructor.</p>
  
  <pre><code>void Display::zoomfunction(bool zoom)
  {
      QMatrix matrix;
  
      if(zoom &amp;&amp; m_zoom_level &lt; 500)
      {
          m_zoom_level = m_zoom_level + 10;
          ui-&gt;graphicsView-&gt;setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
          matrix.scale(m_zoom_level, m_zoom_level);
  
          ui-&gt;graphicsView-&gt;setMatrix(matrix);
          ui-&gt;graphicsView-&gt;scale(1,-1);
      }
      else if(!zoom)
      {
          m_zoom_level = m_zoom_level - 10;
          ui-&gt;graphicsView-&gt;setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
          matrix.scale(m_zoom_level, m_zoom_level);
  
          ui-&gt;graphicsView-&gt;setMatrix(matrix);
          ui-&gt;graphicsView-&gt;scale(1,-1);
      }
  }
  </code></pre>
  
  <p>As you can see above I'm using a <code>QMatrix</code> and scaling that and setting it to the Graphicsview and setting the transformation anchor to under mouse, but its just not working perfectly sometimes if I'm scrolling loads it will just start to zoom in only (which I think is to do with the int looping over or something). </p>
  
  <p>As I said help with this or a good example of scale under mouse would be great.</p>