Home > Enterprise >  svg background for QGraphicsView C
svg background for QGraphicsView C

Time:03-19

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

CodePudding user response:

This is one Example :

First of all add QT = svgwidgets in your .pro.

then add one graphicsView in your UI File :

enter image description here

in mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QGraphicsScene>
#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui
{
class MainWindow;
}
QT_END_NAMESPACE

class MainWindow: public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);

    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QGraphicsScene *scene;
};

#endif // MAINWINDOW_H

in mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGraphicsSvgItem>
#include <QSvgRenderer>

MainWindow::MainWindow(QWidget *parent):
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);

    QGraphicsSvgItem *item = new QGraphicsSvgItem(":/images/images/diagramTool.svg");

    scene->addItem(item);
}

MainWindow::~MainWindow()
{
    delete ui;
}

output :

enter image description here

And there is one easy way you can add this stylesheet in your graphics view :

  background-image: url(":/images/images/diagramTool.svg");
  background-repeat: no-repeat;
  background-position: center;
  border-style:none;

This will add SVG as your background image.

enter image description here

CodePudding user response:

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;
}
  • Related