vertical keypressevent not working on graphicsitem
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/v4...screenshot.png
Code:
QVariant Node
::itemChange(GraphicsItemChange change,
const QVariant
& value
) {
if(change == ItemPositionChange && scene())
{
//value is the new position.
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;
}
}
Code:
{
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:
}
}
Re: vertical keypressevent not working on graphicsitem
Why not simplify itemChange to:
Code:
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;
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;
}
}
Re: vertical keypressevent not working on graphicsitem
wysota thank you. It seems to be working :)
Re: vertical keypressevent not working on graphicsitem
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/v4...reenshot-1.png