具有无响应 keyPressEvent 的 QGraphicsPixmapItem

QGraphicsPixmapItem with non-responsive keyPressEvent

我正在尝试实现一个基本游戏...

我按下键盘按钮,但我添加到我的 QGraphicsScene 的 QGraphicsPixmapItem 不动,我实现了一个keyPressedEvent函数...

我想在按下某个键时移动像素图项目。

代码如下....

marioChar.h(我的像素图项的头文件)

 class marioChar : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
public:
    bool flying;
    explicit marioChar(QPixmap pic);
    void keyPressEvent(QKeyEvent *event);

signals:

public slots:
 };

这是 keypressEvent 处理程序的实现:

   void marioChar::keyPressEvent(QKeyEvent *event)
{
    if(event->key()==Qt::Key_Right)
    {
        if(x()<380)
        {
            this->setPos(this->x()+20,this->y());
        }
    }
}

This is part of the game class where i add the pixmap item to the scene



game::game(int difficulty_Level)
{

       set_Level(difficulty_Level);
       set_Num_Of_Coins(0);
       set_Score(0);
       QGraphicsScene *scene = new QGraphicsScene();
       header = new QGraphicsTextItem();
       header->setZValue(1000);
       timer = new QTimer();
       time = new QTime();
       time->start();
       updateDisplay();
       scene->addItem(header);

       connect(timer,SIGNAL(timeout()),this,SLOT(updateDisplay()));
       timer->start(500);

       QGraphicsView *view = new QGraphicsView(scene);
       scene->setSceneRect(0,0,1019,475);

       QColor skyBlue;
       skyBlue.setRgb(135,206,235);
       view->setBackgroundBrush(QBrush(skyBlue));

       QGraphicsRectItem *floor = new QGraphicsRectItem(0,460,1024,20);
       floor->setBrush(Qt::black);
       scene->addItem(floor);

       player= new marioChar(QPixmap("MarioF.png"));
       player->setPos(0,330);
       player->setZValue(1003);
       scene->addItem(player);

       view->setFixedSize(1024,480);
       view->show();
       player->setFocus();
    }

提前致谢

您的 QGraphicsPixmapItem 不应继承自 QObject。您应该创建一个控制器来管理您的 QGraphicsPixmapItem 并将发出信号并处理游戏中所有 QGraphicsPixmapItem 的插槽。

如果您想让图形项监听按键事件,您需要为图形项设置 QGraphicsItem::ItemIsFocusable 标志。

来自文档:

Note that key events are only received for items that set the ItemIsFocusable flag, and that have keyboard input focus.

以及QGraphicsItem::ItemIsFocusable标志的说明:

The item supports keyboard input focus (i.e., it is an input item). Enabling this flag will allow the item to accept focus, which again allows the delivery of key events to QGraphicsItem::keyPressEvent() and QGraphicsItem::keyReleaseEvent().

从你说: "set the QGraphicsItem::ItemIsFocusable flag to your marioChar object"