简体   繁体   中英

The KeyPressEvent don't work

I have a problem with the KeyPressEvent , I need to move a QGraphicsItem player in my scene, but the program does not use the function KeyPressEvent of class game

File "game.h":

#ifndef GAME_H
#define GAME_H
#include <QLayout>
#include <QTimer>
#include <QGraphicsView>
#include <QAction>
#include <QString>
#include <QLabel>
#include <QKeyEvent>
#include <QGraphicsItem>
#include <strutturaAlieni.h>
#include <naveGiocatore.h>
#include <laser.h>
#include <QWidget>

namespace Ui {
class game;
}

class game : public QWidget
{
    Q_OBJECT

public:
    explicit game(QWidget *parent = 0);
    ~game();

    virtual void keyPressEvent(QKeyEvent *);
}

and the cpp source

void game::keyPressEvent(QKeyEvent *e){
switch(e->key())
{

    case Qt::Key_Left :{
                this->player->moveBy(-5,0);
    break;
    }
    case Qt::Key_Right :{
                this->player->moveBy(5,0);
    break;
    }
  }
 this->player->update();
}

and in the mainwindow.cpp I click the play button that executes this code:

void MainWindow::on_Play_clicked()
{
    game *Gioco=new game;
    Gioco->show();
    Gioco->move(300,0);
 }

Why doesn't the keyPressEvent start?

widget need to have a focus to receive key events. See also QApplication::focusWidget()

If you taking about QGraphicsView then the scene is responsible for focus handling inside of QGraphicsView . See also QGraphicsItem::setFocus

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