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  · 

Printing with Qt

Qt provides extensive cross-platform support for printing. Using the printing systems on each platform, Qt applications can print to attached printers and across networks to remote printers. Qt's printing system also enables PostScript and PDF files to be generated, providing the foundation for basic report generation facilities.

Classes Supporting Printing

The following classes support the selecting and setting up of printers and printing output.

QAbstractPrintDialogBase implementation for print dialogs used to configure printers
QPageSetupDialogConfiguration dialog for the page-related options on a printer
QPrintDialogDialog for specifying the printer's configuration
QPrintEngineDefines an interface for how QPrinter interacts with a given printing subsystem
QPrintPreviewDialogDialog for previewing and configuring page layouts for printer output
QPrintPreviewWidgetWidget for previewing page layouts for printer output
QPrinterPaint device that paints on a printer
QPrinterInfoGives access to information about existing printers

Paint Devices and Printing

In Qt, printers are represented by QPrinter, a paint device that provides functionality specific to printing, such as support for multiple pages and double-sided output. As a result, printing involves using a QPainter to paint onto a series of pages in the same way that you would paint onto a custom widget or image.

Creating a QPrinter

Although QPrinter objects can be constructed and set up without requiring user input, printing is often performed as a result of a request by the user; for example, when the user selects the File|Print... menu item in a GUI application. In such cases, a newly-constructed QPrinter object is supplied to a QPrintDialog, allowing the user to specify the printer to use, paper size, and other printing properties.

     QPrinter printer;

     QPrintDialog *dialog = new QPrintDialog(&printer, this);
     dialog->setWindowTitle(tr("Print Document"));
     if (editor->textCursor().hasSelection())
         dialog->addEnabledOption(QAbstractPrintDialog::PrintSelection);
     if (dialog->exec() != QDialog::Accepted)
         return;

It is also possible to set certain default properties by modifying the QPrinter before it is supplied to the print dialog. For example, applications that generate batches of reports for printing may set up the QPrinter to write to a local file by default rather than to a printer.

Painting onto a Page

Once a QPrinter object has been constructed and set up, a QPainter can be used to perform painting operations on it. We can construct and set up a painter in the following way:

     QPrinter printer(QPrinter::HighResolution);
     printer.setOutputFileName("print.ps");
     QPainter painter;
     painter.begin(&printer);

     for (int page = 0; page < numberOfPages; ++page) {

         // Use the painter to draw on the page.

         if (page != lastPage)
             printer.newPage();
     }

     painter.end();

Since the QPrinter starts with a blank page, we only need to call the newPage() function after drawing each page, except for the last page.

The document is sent to the printer, or written to a local file, when we call end().

Coordinate Systems

QPrinter provides functions that can be used to obtain information about the dimensions of the paper (the paper rectangle) and the dimensions of the printable area (the page rectangle). These are given in logical device coordinates that may differ from the physical coordinates used by the device itself, indicating that the printer is able to render text and graphics at a (typically higher) resolution than the user's display.

Although we do not need to handle the conversion between logical and physical coordinates ourselves, we still need to apply transformations to painting operations because the pixel measurements used to draw on screen are often too small for the higher resolutions of typical printers.

Printer and Painter Coordinate Systems

The paperRect() and pageRect() functions provide information about the size of the paper used for printing and the area on it that can be painted on.

The rectangle returned by pageRect() usually lies inside the rectangle returned by paperRect(). You do not need to take the positions and sizes of these area into account when using a QPainter with a QPrinter as the underlying paint device; the origin of the painter's coordinate system will coincide with the top-left corner of the page rectangle, and painting operations will be clipped to the bounds of the drawable part of the page.

The paint system automatically uses the correct device metrics when painting text but, if you need to position text using information obtained from font metrics, you need to ensure that the print device is specified when you construct QFontMetrics and QFontMetricsF objects, or ensure that each QFont used is constructed using the form of the constructor that accepts a QPaintDevice argument.

Printing from Complex Widgets

Certain widgets, such as QTextEdit and QGraphicsView, display rich content that is typically managed by instances of other classes, such as QTextDocument and QGraphicsScene. As a result, it is these content handling classes that usually provide printing functionality, either via a function that can be used to perform the complete task, or via a function that accepts an existing QPainter object. Some widgets provide convenience functions to expose underlying printing features, avoiding the need to obtain the content handler just to call a single function.

The following table shows which class and function are responsible for printing from a selection of different widgets. For widgets that do not expose printing functionality directly, the content handling classes containing this functionality can be obtained via a function in the corresponding widget's API.

WidgetPrinting functionAccepts
QGraphicsViewQGraphicsView::render()QPainter
QSvgWidgetQSvgRenderer::render()QPainter
QTextEditQTextDocument::print()QPrinter
QTextLayoutQTextLayout::draw()QPainter
QTextLineQTextLine::draw()QPainter

QTextEdit requires a QPrinter rather than a QPainter because it uses information about the configured page dimensions in order to insert page breaks at the most appropriate places in printed documents.

[Previous: Styling] [The Paint System]

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. Microsoft ouvre aux autres compilateurs C++ AMP, la spécification pour la conception d'applications parallèles C++ utilisant le GPU 22
  2. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  3. RIM : « 13 % des développeurs ont gagné plus de 100 000 $ sur l'AppWord », Qt et open-source au menu du BlackBerry DevCon Europe 0
  4. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 10
  5. 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
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
Page suivante

Le Qt Quarterly au hasard

Logo

Déployer dans le Bazaar

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. 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