KeyPressEvent不起作用

时间:2014-10-29 15:30:22

标签: c++ qt

我对KeyPressEvent有疑问,我需要在我的场景中移动QGraphicsItem玩家,但该程序不使用类KeyPressEvent的{​​{1}}函数

文件" game.h":

game

和cpp源

#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 *);
}

并在mainwindow.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();
}

为什么void MainWindow::on_Play_clicked() { game *Gioco=new game; Gioco->show(); Gioco->move(300,0); } 没有开始?

1 个答案:

答案 0 :(得分:1)

小部件需要focus才能接收关键事件。另请参阅QApplication::focusWidget()

如果您开始使用QGraphicsView,则scene负责QGraphicsView内的焦点处理。 另请参阅QGraphicsItem::setFocus

相关问题