【问题标题】:QGraphicsPixmapItem with non-responsive keyPressEventQGraphicsPixmapItem 与非响应 keyPressEvent
【发布时间】:2015-03-20 14:04:03
【问题描述】:

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

我按下键盘按钮,但 QGraphicsPixmapItem 我添加到我的 QGraphicsScene 不动,我实现了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();
    }

提前致谢

【问题讨论】:

标签: c++ qt qt-creator


【解决方案1】:
【解决方案2】:

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

【讨论】:

  • 我更新了我的答案,以更好地反映我想说的话。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    相关资源
    最近更新 更多