(Pure) Abstract class that inherits from QGraphicsItem



  • Is it possible to make an own custom class abstract, inherit mousePressEvents, paint() and boundingRect() from QGraphicsItem and define concrete classes which inherit from my abstract base class AND still inherit from QGraphicsItem?

    For example:
    MyItem.h

    class MyItem: public QGraphicsItem
    {
    public:
        MyItem();
    
        virtual QRectF boundingRect() const = 0; // pure virtual to override in concrete class
        virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                   QWidget *widget);
        
    protected:
        void mousePressEvent(QGraphicsSceneMouseEvent *event);
    
    private:
        // my member_vars
    };
    

    Concrete class(es)

    class MyShapeA: public MyItem
    {
    public:
       MyShapeA();
       QRectF boundingRect(.....);
       void paint(......);
    };
    
    class MyShapeB: public MyItem
    {
    public:
        MyShapeB();
    
        QRectF boundingRect(.....);
        void paint(......);
    };
    

    When it's done, I want to generate random (concrete) objects from MyItem / my concrete classes. All concrete classes should have a different boundingRect, paint and members but the same behavior for example on mouseEvents.
    Do I need my abstract base class for that or is it better to let all concrete classes inherit directly from QGrahicsItem and skip the MyItem class between them.

    I have worries that it will cause problems later, because boundingRect is overridden and inherited from QGraphicsItem already (inherit from 2 QObject classes).


  • Lifetime Qt Champion

    Hi
    As long as you dont do multiple inheritance ,
    i think you base class design should work just fine.
    However, make sure to overrride
    int QGraphicsItem::type() const pr concrete class to make sure
    qgraphicsitem_cast() works.



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