I'm currently working on a program for making graphs(figure 1), but I'm running into some problems when using the itemChange and KeyPressEvent from the QGraphicsItem class.

I'm trying to implement a "snap to grid" feature in the map. It works when I move the nodes with the mouse, but not when using the keyboard arrows. Specifically moving up and down with the keyboard doesn't work. There is no problem in moving the node left and right with the keyboard. Moving a node up and down only works when I remove the "return newPos" line. I don't understand why.

The code I'm using can be found a little further down.

figure 1: Map Editor program


Qt Code:
  1. QVariant Node::itemChange(GraphicsItemChange change, const QVariant& value)
  2. {
  3. if(change == ItemPositionChange && scene())
  4. {
  5. //value is the new position.
  6. QPointF newPos = value.toPointF();
  7. if(static_cast<int>(x() - newPos.x()) % GridScene::GridSize == 0)
  8. {
  9. newPos.setX(newPos.rx());
  10. newPos.setY(y());
  11. }
  12. else if(static_cast<int>(y() - newPos.y()) % GridScene::GridSize == 0)
  13. {
  14. newPos.setX(x());
  15. newPos.setY(newPos.ry());
  16. }
  17. else
  18. {
  19. newPos.setX(x());
  20. newPos.setY(y());
  21. }
  22.  
  23. updateToolTip();
  24.  
  25. return newPos;
  26.  
  27. }
  28.  
  29. return QGraphicsItem::itemChange(change, value);
  30. }
To copy to clipboard, switch view to plain text mode 

Qt Code:
  1. void Node::keyPressEvent(QKeyEvent* event)
  2. {
  3. switch(event->key())
  4. {
  5. case Qt::Key_Left:
  6. moveBy(-GridScene::GridSize, 0);
  7. break;
  8.  
  9. case Qt::Key_Right:
  10. moveBy(GridScene::GridSize, 0);
  11. break;
  12.  
  13. case Qt::Key_Up:
  14. moveBy(0, -GridScene::GridSize);
  15. break;
  16.  
  17. case Qt::Key_Down:
  18. moveBy(0, GridScene::GridSize);
  19. break;
  20.  
  21. default:
  22. QGraphicsItem::keyPressEvent(event);
  23. }
  24. }
To copy to clipboard, switch view to plain text mode