Subclassing QGraphicsScene



  • Hey all,

    So I am trying to write a subclass of QGraphicsScene, so that I can get key and mouse press events, and send them out with custom signals to the main UI. However, I can't for the life of me find a straightforward answer on how to do it, so here I am. This is what I have so far:

    @
    #include <QtGui>
    #include <QGraphicsScene>
    class QKeyEvent;
    class QGraphicsSceneMouseEvent;

    class MapScene : public QGraphicsItem {
    Q_OBJECT

    public:
    MapScene(QObject *parent = 0);
    ~MapScene();

    signals:
    void deselectPoints();
    void selectPoints(QRectF);
    void sendPoint(QPoint);

    protected:
    void keyPressEvent(QKeyEvent *event);
    void mousePressEvent(QGraphicsSceneMouseEvent *event);
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
    };
    @

    I know this is incorrect, but no matter how I write the constructor declarations or class headers I get various compile errors- either undefined references for the constructor/deconstructor, or no know conversion to QObject, or others. Any help? I feel this is a pretty basic question which is why I'm surprised it's proving difficult.



  • Do you have actual code for constructor ad destructor?
    Did you take a look at examples (Diagram Scene Example has this covered pretty good)?
    Q_OBJECT is not needed ( not sure if it's even possible).



  • So you have
    @class MapScene : public QGraphicsItem @
    QGraphics_Item_



  • It turns out the Q_OBJECT was needed (although I agree it shouldn't be). I kept getting errors saying it needed to be there if I eliminated it. But it turns out the constructor/destructor both in this and in the .cpp file were incorrect, so it basically thought they weren't there. I also needed it to extend QGraphicsScene, not QGraphicsItem. Works now though... thank you for the tip!



  • The Q_OBJECT macro is only for QObject-based classes. QGraphicsItem is not a QObject based class.

    Since it isn't, it also can't have signals. Without the Q_OBJECT macro, the C++ compiler will not understand what to do about those signals, and throw errors. With the Q_OBJECT macro, the compiler is pacified, but since you are not actually having a QObject-based class, they won't work.

    If you need signals in your class, change the base class to QGraphicsObject.



  • I actually ended up making the base class QGraphicsScene, because really that's what I was subclassing anyway, which resolved the conflict.

    I had still been wondering what the macro was doing, thank you for the explanation.



  • The Q_OBJECT macro does more than I wrote. Basically, it sets everything up so Qt's meta object system can be used.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.