PDA

View Full Version : vertical keypressevent not working on graphicsitem



creatio.x
23rd December 2009, 11:12
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
http://img.photobucket.com/albums/v421/notorious_godF/Tha_Rest/screenshot.png


QVariant Node::itemChange(GraphicsItemChange change, const QVariant& value)
{
if(change == ItemPositionChange && scene())
{
//value is the new position.
QPointF newPos = value.toPointF();
if(static_cast<int>(x() - newPos.x()) % GridScene::GridSize == 0)
{
newPos.setX(newPos.rx());
newPos.setY(y());
}
else if(static_cast<int>(y() - newPos.y()) % GridScene::GridSize == 0)
{
newPos.setX(x());
newPos.setY(newPos.ry());
}
else
{
newPos.setX(x());
newPos.setY(y());
}

updateToolTip();

return newPos;

}

return QGraphicsItem::itemChange(change, value);
}


void Node::keyPressEvent(QKeyEvent* event)
{
switch(event->key())
{
case Qt::Key_Left:
moveBy(-GridScene::GridSize, 0);
break;

case Qt::Key_Right:
moveBy(GridScene::GridSize, 0);
break;

case Qt::Key_Up:
moveBy(0, -GridScene::GridSize);
break;

case Qt::Key_Down:
moveBy(0, GridScene::GridSize);
break;

default:
QGraphicsItem::keyPressEvent(event);
}
}

wysota
23rd December 2009, 11:48
Why not simplify itemChange to:

QVariant Node::itemChange(GraphicsItemChange change, const QVariant& value)
{
if(change == ItemPositionChange && scene())
{
//value is the new position.
QPoint newPos = value.toPointF(); // note - no "F"
QPoint offset(newPos.x() % GridScene::GridSize, newPos.y() % GridScene::GridSize);
// if you want real positions, substitute mod with a different operation to calculate offset
newPos -= offset;
QPoint corr;
if(offset.x()>0.5*GridScene::GridSize) corr.setX(GridScene::GridSize);
if(offset.y()>0.5*GridScene::GridSize) corr.setY(GridScene::GridSize);
newPos += corr;
return newPos;
}
return QGraphicsItem::itemChange(change, value);
}

creatio.x
24th December 2009, 14:27
wysota thank you. It seems to be working :)

creatio.x
25th December 2009, 11:23
hmm, now I have another problem. The edge(line) in the scene doesn't snap to the grid. It moves with the size of GridScene::Gridsize, but not on the lines. See figure 2

figure 2
http://img.photobucket.com/albums/v421/notorious_godF/Tha_Rest/screenshot-1.png