Move a QGraphicsPixmapItem through keyboard

414 views Asked by At

I have a a character added via QgraphicsPixmapitem and now I want to move it by pressing the arrow keys on the keyboard. But I can't find a way. It gives compilation error. Help me please!

moveship.h (header file for my QPixmapItem)

#ifndef MOVESHIP_H
#define MOVESHIP_H
#include <QGraphicsPixmapItem>

class moveship: public QGraphicsPixmapItem
{
    public:
    void keyPressEvent(QKeyEvent *event);
};
#endif // MOVESHIP_H

I am just checking if it recognises any key press or not.

Implementation of keyPressEvent:

#include "moveship.h"
#include <QDebug>

void moveship::keyPressEvent(QKeyEvent *event)
{
    qDebug() << "moved";
}

My main source file:

#include<QApplication>
#include<QGraphicsScene>
#include<QGraphicsView>
#include<QGraphicsPixmapItem>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene * scene = new QGraphicsScene();
    QGraphicsView * view = new QGraphicsView(scene);

    QPixmap q = QPixmap("://images/player.png");
    if(q.isNull())
    {
        printf("null\n");
    }
    else
    {
        moveship * player = new moveship(q);
        scene->addItem(player);
    }

    view->resize(500,500);
    view->show();

    return a.exec();
}

Please Help :(

Edit:

The compilation error which I get is:

error: no matching function for call to 'moveship::moveship(QPixmap&)'
moveship * player = new moveship(q);

1

There are 1 answers

3
dazewell On

Well, there's nothing common in the question you ask and the error you get. As I see, you don't have any constructor of your class moveship, and that's exactly what compiler is telling to you. There's got to be smth like:

moveship(const QPixmap & pixmap, QGraphicsItem * parent = 0)

in the header of your class with some implementation, of course and as I see, it's trivial:

moveship::moveship(const QPixmap & pixmap, QGraphicsItem * parent = 0) 
                 : QGraphicsItem(pixmap, parent);

That's the base knowledge you should have when using c++. Here's nothing special about Qt. I advise you to learn c++ a bit.

BTW, reimplemented ...event(...) functions is recommended to place in the protected part of the class and also declare it to be virtual.