Bar
Bar

Reputation: 69

QGraphicsPixmapItem with non-responsive keyPressEvent

I'm trying to implement a basic game...

I press keyboard buttons but the QGraphicsPixmapItem I added to my QGraphicsScene doesn't move, I have implemented a keyPressedEvent function...

I want to move the pixmap item when a key is pressed.

code is below....

marioChar.h (the header file for my pixmap item)

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

signals:

public slots:
 };

This is the implementation of the keypressEvent handler:

   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();
    }

Thanks in advance

Upvotes: 0

Views: 527

Answers (3)

Bar
Bar

Reputation: 69

As thuga said: "set the QGraphicsItem::ItemIsFocusable flag to your marioChar object"

Upvotes: 0

Chris
Chris

Reputation: 279

Your QGraphicsPixmapItem should not inherit from QObject. You should create a controller that manages your QGraphicsPixmapItem and will emit signals and handle the slots for all QGraphicsPixmapItem's in your game.

Upvotes: 0

Related Questions