具有非响应键PressEvent的QGraphicsPixmapItem

QGraphicsPixmapItem with non-responsive keyPressEvent

本文关键字:PressEvent QGraphicsPixmapItem 响应      更新时间:2023-10-16

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

我按下键盘按钮,但我添加到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();
    }

提前感谢

如果希望图形项监听关键事件,则需要将QGraphicsItem::ItemIsFocusable标志设置为图形项。

来自文档:

请注意,键事件仅针对设置ItemIsFocusable标志并且具有键盘输入焦点的项目接收

以及QGraphicsItem::ItemIsFocusable标志的描述:

该项支持键盘输入焦点(即,它是一个输入项)。启用此标志将允许项目接受焦点,这再次允许将关键事件传递到QGraphicsItem::keyPressEvent()和QGraphicsItem::keyReleaseEvent()

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

正如thuga所说:"将QGraphicsItem::ItemIsFocusable标志设置为您的marioChar对象"