Evgenii Legotckoi
Evgenii LegotckoiMarch 20, 2016, 12:31 p.m.

Qt/C++ - Lesson 044. Saving objects from QGraphicsScene into SVG

Using Qt, you can save the contents of the graphic scene QGraphicsScene to SVG vector graphics files that are opened without problems after such editors as CorelDraw. I propose to write a small application that will save the contents of the graphic scenes in SVG file format, and then open it using CorelDraw.

Project structure

  • SvgExample.pro - Project Profile;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - source file of the main application window, in which all the action will take place;
  • mainwindow.ui - file forms the main application window;
  • main.cpp - the main boot file source.

mainwindow.ui

In the interface designer we creates button, which will open a dialog box in which we choose the path to save the SVG file. As well as set widget QGraphicsView, in which the graphic scene will be placed.

SvgExample.pro

The project profile is absolutely necessary to connect the SVG module to be able to work with classes of vector graphics.

#-------------------------------------------------
#
# Project created by QtCreator 2016-03-09T23:52:59
#
#-------------------------------------------------

QT       += core gui svg

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = SvgExample
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.h

So, in the header of the main application window connect QGraphicsScene , QGraphicsRectItem , QSvgGenerator , QFileDialog and QPainter .

On the graphics it will create two rectangles that need to be saved in the SVG file. Saving will be made in the button pressing processing slot, which will cause a dialog box to select the ways to preserve the SVG file.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QSvgGenerator>
#include <QFileDialog>
#include <QPainter>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_saveButton_clicked();

private:
    Ui::MainWindow *ui;
    QGraphicsScene *scene;  
    QString path;           // The path to save the file
};

#endif // MAINWINDOW_H

mainwindow.cpp

To set the service parameters and draw graphic objects with a graphic scene used QSvgGenerator class object, but for data transfer and direct rendering in this object will be used by QPainter class object, which set a target to which the rendering will be made using the begin() method, and the purpose of rendering the object itself is directly QSvgGenerator class. Drawing will proizodit using the method of graphic scene render() , through QPainter .

#include "mainwindow.h"
#include "ui_mainwindow.h"

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

    scene = new QGraphicsScene();
    ui->graphicsView->setScene(scene);
    scene->setSceneRect(0,0,400,400);

    // Create the first red rectangle on the graphic scene
    QGraphicsRectItem *rect1 = new QGraphicsRectItem();
    rect1->setRect(10,50,100,50);
    rect1->setBrush(QBrush(Qt::red));
    rect1->setPen(QPen(QBrush(Qt::black),2));
    scene->addItem(rect1);

    // And create a second blue rectangle on the graphic scene
    QGraphicsRectItem *rect2 = new QGraphicsRectItem();
    rect2->setRect(150,100,115,75);
    rect2->setBrush(QBrush(Qt::blue));
    rect2->setPen(QPen(QBrush(Qt::black),2));
    scene->addItem(rect2);
}

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

void MainWindow::on_saveButton_clicked()
{
    // Take file path and name that will create
    QString newPath = QFileDialog::getSaveFileName(this, trUtf8("Save SVG"),
        path, tr("SVG files (*.svg)"));

    if (newPath.isEmpty())
        return;

    path = newPath;

    QSvgGenerator generator;        // Create a file generator object
    generator.setFileName(path);    // We set the path to the file where to save vector graphics
    generator.setSize(QSize(scene->width(), scene->height()));  // Set the dimensions of the working area of the document in millimeters
    generator.setViewBox(QRect(0, 0, scene->width(), scene->height())); // Set the work area in the coordinates
    generator.setTitle(trUtf8("SVG Example"));                          // The title document 
    generator.setDescription(trUtf8("File created by SVG Example"));    

    QPainter painter;
    painter.begin(&generator); 
    scene->render(&painter);   
    painter.end();              

    // At the end we get a vector drawing file with the contents of the graphic scenes
}

Result

As a result of this code you will get the SVG file that successfully opens in CorelDraw.

  1. SvgReader on the Qt. Loading data from SVG file into QGraphicsScene

Video

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

N
  • May 31, 2017, 6:13 p.m.

Добрый вечер. Встал вопрос. Каким образом сохранить координаты объектов, потому что в следующем уроке объекты на сцене будут находиться все в одном месте из которого их еще придется перетаскивать

Evgenii Legotckoi
  • June 1, 2017, 2:29 a.m.

Координаты объектов в данном случае нормально сохраняются. В конце статьи есть урок по восстановлению данных из SVG файла, изучите его. Там показано, как расположить объекты на графической сцене во время восстановления данных.

АО
  • March 13, 2020, 5:20 a.m.

Здравствуйте!
Как можно добавить текст туда?
Хочу попробовать нарисовать граф и обозначить вершины с дугами.

Добрый день.
Текст можно добавить на графическубюю сцену с помощью QGraphicsTextItem.

МЧ
  • May 17, 2020, 2:12 p.m.

Добрый день!
А не подскажете как можно сохранить фон, если это моя собственная картинка? При сохранении просто однотонного фона, не картинки все работает хорошо.

Evgenii Legotckoi
  • May 18, 2020, 3:31 a.m.

Добрый день.
Не подскажу. Могу только направить. Для это нужно в каком-нибудь популярном svg редакторе смотреть, как будет сохраняться ихображение, и потом попытаться повторить тоже самое средствами Qt.
Вполне возможно, что изображение там или отдельно будет сохраняться или будет как-то встраиваться в SVG файл.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 4:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 4:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 4:35 a.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks