Hi!

I'm having problems with my QGraphicsView and some mouse events. Basically I want to zoom and pan my view and also handle the items events.

I want the following behavior: The graphics view should only receive the events while my space button is pressed. So if you want to pan/zoom you should press space and either the right or left mouse button (left = pan, right = zoom). Otherwise the items should receive the events.

My items don't implement any event handling at the moment so they are using the standard implementation.

The code for my view:

Qt Code:
  1. //--------------------------------------------------------------------------------
  2. void GraphicsView::mousePressEvent(QMouseEvent *event)
  3. {
  4. if(_key != Qt::Key_Space)
  5. {
  6. QGraphicsView::mousePressEvent(event);
  7. event->ignore();
  8. return;
  9. }
  10.  
  11. //save mouse position
  12. _last_position = event->pos();
  13. }
  14.  
  15. //--------------------------------------------------------------------------------
  16. void GraphicsView::mouseReleaseEvent(QMouseEvent *event)
  17. {
  18. if(_key != Qt::Key_Space)
  19. {
  20. QGraphicsView::mouseReleaseEvent(event);
  21. event->ignore();
  22. return;
  23. }
  24.  
  25. setCursor(_default_cursor);
  26. }
  27.  
  28. //--------------------------------------------------------------------------------
  29. void GraphicsView::mouseMoveEvent(QMouseEvent *event)
  30. {
  31. if(_key != Qt::Key_Space)
  32. {
  33. QGraphicsView::mouseMoveEvent(event);
  34. event->ignore();
  35. return;
  36. }
  37.  
  38. int dx = event->x() - _last_position.x();
  39. int dy = event->y() - _last_position.y();
  40.  
  41. //save mouse position
  42. _last_position = event->pos();
  43.  
  44. qDebug() << "pos: " << event->pos().x() << " " << event->pos().y();
  45.  
  46. if (event->buttons() == Qt::LeftButton)
  47. {
  48. setCursor(_move_cursor);
  49. pan(dx, dy);
  50. }
  51. else if (event->buttons() == Qt::RightButton)
  52. {
  53. zoom(dx);
  54. }
  55. }
  56.  
  57. //--------------------------------------------------------------------------------
  58. void GraphicsView::keyPressEvent(QKeyEvent *event)
  59. {
  60. _key = event->key();
  61. }
  62.  
  63. //--------------------------------------------------------------------------------
  64. void GraphicsView::keyReleaseEvent(QKeyEvent *event)
  65. {
  66. _key = 0;
  67. }
To copy to clipboard, switch view to plain text mode 

Now my main problem is that I receive all events as expected but during my views mousMoveEvent which I handle only while space is pressed my events position isn't correct. It stays always the same. If I don't have space pressed the events position changes depending on the mouse position.

I have no idea what I'm doing wrong. If I uncomment all the QGraphicsView::mouseXEvent(event) it works fine. But if I deliver the events to my items if space is not pressed it doesn't work.