I try to move an item in a scene and for that, I use QKeypressEvent
and moveBy
that works both perfectly but I'd like to recover the "key press event", so I decided first, to use a boolean that returns true when the key is pressed and false when it's not, and then to create a new function where I call the moveBy
if my boolean is true, but unfortunately is doesn't work.
This is what I've done in my file.cpp
Perso::Perso()
{
right= false;
left= false;
up= false;
down= false;
moveOnMap();
setFlag(QGraphicsItem::ItemIsFocusable);
}
void Perso::moveOnMap(){
if (left) {
moveBy(-10,0);
}
if (right) {
moveBy(10,0);
}
if (up) {
moveBy(0, -10);
}
if (down) {
moveBy(0, +10);
}
}
void Perso::keyPressEvent(QKeyEvent *event){
switch(event->key()){
case Qt::Key_Up:
up=true;
//moveBy(0, -10);
break;
case Qt::Key_Right:
right=true;
// moveBy(10,0);
break;
case Qt::Key_Left:
left=true;
//moveBy(-10,0);
break;
case Qt::Key_Down:
down= true;
//moveBy(0, 10);
break;
}
update();
}
void Perso::keyReleaseEvent(QKeyEvent *event){
switch(event->key()){
case Qt::Key_Up:
up=false;
break;
case Qt::Key_Right:
right= false;
break;
case Qt::Key_Left:
left= false;
break;
case Qt::Key_Down:
down= false;
break;
}
}
Anyone can help me to understand where I am wrong?