首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无响应的QGraphicsPixmapItem keyPressEvent

无响应的QGraphicsPixmapItem keyPressEvent
EN

Stack Overflow用户
提问于 2015-03-20 14:04:03
回答 3查看 395关注 0票数 0

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

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

当按下键时,我想移动像素映射项。

代码在下面..。

H(我的像素映射项的头文件)

代码语言:javascript
复制
 class marioChar : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
public:
    bool flying;
    explicit marioChar(QPixmap pic);
    void keyPressEvent(QKeyEvent *event);

signals:

public slots:
 };

这是keypressEvent处理程序的实现:

代码语言:javascript
复制
   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();
    }

提前感谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-03-20 14:21:32

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

从医生那里:

http://doc.qt.io/qt-5/qgraphicsitem.html#keyPressEvent

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

http://qt-project.org/doc/qt-4.8-snapshot/qgraphicsitem.html#GraphicsItemFlag-enum

票数 3
EN

Stack Overflow用户

发布于 2015-03-20 14:06:58

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

票数 0
EN

Stack Overflow用户

发布于 2015-03-20 14:25:29

如前所述:“将QGraphicsItem::ItemIsFocusable标志设置为您的marioChar对象”

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29168390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档