简体   繁体   中英

Move an item in a scene Qt

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?

I can't see here that you call your moveOnMap(); If in your original code you don't call this method that it is normal that it is not work. You call it only in constructor but you should call this method every key pressing. So try to call this method in your key events:

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;
    }

    moveOnMap();
    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;
    }
    moveOnMap();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM