Hi!

I'm coming from experience with Cocoa and Winforms, and I'm just starting with Qt. I have set up a subclass of QGraphicsView. I'll show the relevant functions below. The issue I'm having is twofold:

If I click item 1 and drag, item 2 moves. If I click item 2 and drag, item 1 moves.

If I use the mousewheel to zoom, the mouseMoveEvent starts being called whenever the mouse moves even if a button is not held.

I've been staring at this for over an hour, having tried different things, like forcing mouseTracking to false at the end of the wheelevent, which didn't change anything.

Qt Code:
  1. EditorView::EditorView(QWidget* parent) :
  2. {
  3. setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
  4.  
  5. QGraphicsScene* scene = new QGraphicsScene(this);
  6. setScene(scene);
  7. setSceneRect(INT_MIN / 2, INT_MIN / 2, INT_MAX, INT_MAX);
  8.  
  9. item1->setRect(250.0, 250.0, 50.0, 50.0);
  10. item1->setFlag(QGraphicsItem::ItemIsMovable);
  11.  
  12. item2->setRect(150.0, 150.0, 50.0, 50.0);
  13. item2->setFlag(QGraphicsItem::ItemIsMovable);
  14.  
  15. setCursor(Qt::OpenHandCursor);
  16. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  17. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  18. }
  19.  
  20. void EditorView::mousePressEvent(QMouseEvent* event)
  21. {
  22. QGraphicsView::mousePressEvent(event);
  23.  
  24. m_lastDragPos = event->pos();
  25. }
  26.  
  27. void EditorView::mouseMoveEvent(QMouseEvent* event)
  28. {
  29. QPointF delta = mapToScene(event->pos()) - mapToScene(m_lastDragPos);
  30. PanView(delta);
  31. m_lastDragPos = event->pos();
  32. }
  33.  
  34. void EditorView::wheelEvent(QWheelEvent* event)
  35. {
  36. int delta = event->delta() / 120;
  37. ScaleView(delta);
  38. }
  39.  
  40. void EditorView::PanView(QPointF delta)
  41. {
  42. QPoint viewCenter(viewport()->width() / 2 - delta.x(), viewport()->height() / 2 - delta.y());
  43. QPointF newCenter = mapToScene(viewCenter);
  44. centerOn(newCenter);
  45. }
  46.  
  47. void EditorView::ScaleView(int delta)
  48. {
  49. bool zoomIn = (delta > 0);
  50. delta = abs(delta);
  51. ViewportAnchor oldAnchor = transformationAnchor();
  52. setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
  53. for(int i = 0; i < delta; ++i)
  54. {
  55. if(zoomIn)
  56. {
  57. scale(1.10, 1.10);
  58. }
  59. else
  60. {
  61. scale(0.90, 0.90);
  62. }
  63. }
  64. setTransformationAnchor(oldAnchor);
  65. }
To copy to clipboard, switch view to plain text mode