Search code examples
c++qtsvgqgraphicsview

svg background for QGraphicsView C++


I would like to put an svg image as background to my QGraphicsView without repetition and preserving the ratio. Can you help me? Thanks.


Solution

  • To put a background that fits the size of the object I created a class that inherits from QGraphicsScene and I rewrote drawBackground by putting my svg image in it. myscene.h

    class myscene : public QGraphicsScene
    {
     public:
       myscene();
       ~myscene();
    
       void drawBackground(QPainter *painter, const QRectF &rect);
    };
    

    myscene.cpp

    myscene::myscene():QGraphicsScene()
    {
    }
    
    myscene::~myscene()
    {
    }
    
    void myscene::drawBackground(QPainter *painter, const QRectF &rect)
    {
        painter->drawImage(rect, QImage(":myPathImage.svg"));
    }
    

    Then in my QGraphicsView I passed it this scene and it works. myview.h:

    class myview : public QGraphicsView
    {
    private :
       myscene* _scene;
    
    public: 
       myview();
       ~myview();
    
    };
    

    myview.cpp:

    myview::myview() : QGraphicsView()
    {
      _scene = new myscene();
    
      this->setScene(_scene);
      this->showMaximized();
    }
    
    myview::~myview()
    {
       delete _scene;
    }