按键事件不起作用

The KeyPressEvent don't work

本文关键字:不起作用 事件      更新时间:2023-10-16

我的KeyPressEvent有问题,我需要在场景中移动QGraphicsItem播放器,但程序没有使用game 类的函数KeyPressEvent

文件"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 *);
}

和cpp源

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

在主窗口.cpp中,我单击执行以下代码的播放按钮:

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

为什么keyPressEvent没有启动?

小部件需要有一个焦点来接收关键事件。另请参阅QApplication::focusWidget()

如果拍摄QGraphicsView,则场景负责QGraphicsView内部的焦点处理。另请参阅QGraphicsItem::setFocus