Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

SVG Generator Example

Files:

The SVG Generator example shows how to add SVG file export to applications.

Scalable Vector Graphics (SVG) is an XML-based language for describing two-dimensional vector graphics. Qt provides classes for rendering and generating SVG drawings. This example allows the user to create a simple picture and save it to an SVG file.

The example consists of two classes: Window and DisplayWidget.

The Window class contains the application logic and constructs the user interface from a Qt Designer UI file as described in the Qt Designer manual. It also contains the code to write an SVG file.

The DisplayWidget class performs all the work of painting a picture on screen. Since we want the SVG to resemble this picture as closely as possible, we make this code available to the Window class so that it can be used to generate SVG files.

The DisplayWidget Class

The DisplayWidget class displays a drawing consisting of a selection of elements chosen by the user. These are defined using Shape and Background enums that are included within the class definition:

 class DisplayWidget : public QWidget
 {
     Q_OBJECT

 public:
     enum Shape { House = 0, Car = 1 };
     enum Background { Sky = 0, Trees = 1, Road = 2 };

     DisplayWidget(QWidget *parent = 0);
     QColor color() const;
     void paint(QPainter &painter);

 public slots:
     void setBackground(Background background);
     void setColor(const QColor &color);
     void setShape(Shape shape);

 protected:
     void paintEvent(QPaintEvent *event);

 private:
     Background background;
     QColor shapeColor;
     Shape shape;
     QHash<Shape,QPainterPath> shapeMap;
     QPainterPath moon;
     QPainterPath tree;
 };

Much of this class is used to configure the appearance of the drawing. The paintEvent() and paint() functions are most relevant to the purpose of this example, so we will describe these here and leave the reader to look at the source code for the example to see how shapes and colors are handled.

We reimplement the QWidget::paintEvent() function to display the drawing on screen:

 void DisplayWidget::paintEvent(QPaintEvent * /* event */)
 {
     QPainter painter;
     painter.begin(this);
     painter.setRenderHint(QPainter::Antialiasing);
     paint(painter);
     painter.end();
 }

Here, we only construct a QPainter object, begin painting on the device and set a render hint for improved output quality before calling the paint() function to perform the painting itself. When this returns, we close the painter and return.

The paint() function is designed to be used for different painting tasks. In this example, we use it to draw on a DisplayWidget instance and on a QSvgGenerator object. We show how the painting is performed to demonstrate that there is nothing device-specific about the process:

 void DisplayWidget::paint(QPainter &painter)
 {
     painter.setClipRect(QRect(0, 0, 200, 200));
     painter.setPen(Qt::NoPen);

     switch (background) {
     case Sky:
     default:
         painter.fillRect(QRect(0, 0, 200, 200), Qt::darkBlue);
         painter.translate(145, 10);
         painter.setBrush(Qt::white);
         painter.drawPath(moon);
         painter.translate(-145, -10);
         break;
     case Trees:
     {
         painter.fillRect(QRect(0, 0, 200, 200), Qt::darkGreen);
         painter.setBrush(Qt::green);
         painter.setPen(Qt::black);
         for (int y = -55, row = 0; y < 200; y += 50, ++row) {
             int xs;
             if (row == 2 || row == 3)
                 xs = 150;
             else
                 xs = 50;
             for (int x = 0; x < 200; x += xs) {
                 painter.save();
                 painter.translate(x, y);
                 painter.drawPath(tree);
                 painter.restore();
             }
         }
         break;
     }
     case Road:
         painter.fillRect(QRect(0, 0, 200, 200), Qt::gray);
         painter.setPen(QPen(Qt::white, 4, Qt::DashLine));
         painter.drawLine(QLine(0, 35, 200, 35));
         painter.drawLine(QLine(0, 165, 200, 165));
         break;
     }

     painter.setBrush(shapeColor);
     painter.setPen(Qt::black);
     painter.translate(100, 100);
     painter.drawPath(shapeMap[shape]);
 }

The Window Class

The Window class represents the example's window, containing the user interface, which has been created using Qt Designer:

 class Window : public QWidget, private Ui::Window
 {
     Q_OBJECT

 public:
     Window(QWidget *parent = 0);

 public slots:
     void saveSvg();
     void updateBackground(int background);
     void updateColor();
     void updateShape(int shape);

 private:
     QString path;
 };

As with the DisplayWidget class, we concentrate on the parts of the code which are concerned with painting and SVG generation. In the Window class, the saveSvg() function is called whenever the Save As... button is clicked; this connection was defined in the window.ui file using Qt Designer.

The start of the saveSvg() function performs the task of showing a file dialog so that the user can specify a SVG file to save the drawing to.

 void Window::saveSvg()
 {
     QString newPath = QFileDialog::getSaveFileName(this, tr("Save SVG"),
         path, tr("SVG files (*.svg)"));

     if (newPath.isEmpty())
         return;

     path = newPath;

     QSvgGenerator generator;
     generator.setFileName(path);
     generator.setSize(QSize(200, 200));
     generator.setViewBox(QRect(0, 0, 200, 200));
     generator.setTitle(tr("SVG Generator Example Drawing"));
     generator.setDescription(tr("An SVG drawing created by the SVG Generator "
                                 "Example provided with Qt."));
     QPainter painter;
     painter.begin(&generator);
     displayWidget->paint(painter);
     painter.end();
 }

In the rest of the function, we set up the generator and configure it to generate output with the appropriate dimensions and write to the user-specified file. We paint on the QSvgGenerator object in the same way that we paint on a widget, calling the DisplayWidget::paint() function so that we use exactly the same code that we used to display the drawing.

The generation process itself begins with the call to the painter's begin() function and ends with call to its end() function. The QSvgGenerator paint device relies on the explicit use of these functions to ensure that output is written to the file.

Further Reading

The SVG Viewer Example shows how to display SVG drawings in an application, and can be used to show the contents of SVG files created by this example.

See the QtSvg module documentation for more information about SVG and Qt's SVG classes.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 64
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. La rubrique Qt a besoin de vous ! 1
Page suivante

Le Qt Developer Network au hasard

Logo

Combiner licence, à propos et fermer d'une autre manière

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.6
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web