QPrinter Class

The QPrinter class is a paint device that paints on a printer. More...

Header: #include <QPrinter>
CMake: find_package(Qt6 COMPONENTS PrintSupport REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::PrintSupport)
qmake: QT += printsupport
Inherits: QPagedPaintDevice

Note: All functions in this class are reentrant.

Public Types

enum ColorMode { Color, GrayScale }
enum DuplexMode { DuplexNone, DuplexAuto, DuplexLongSide, DuplexShortSide }
enum OutputFormat { NativeFormat, PdfFormat }
enum PageOrder { FirstPageFirst, LastPageFirst }
enum PaperSource { Auto, Cassette, Envelope, EnvelopeManual, FormSource, …, LastPaperSource }
enum PrintRange { AllPages, Selection, PageRange, CurrentPage }
enum PrinterMode { ScreenResolution, PrinterResolution, HighResolution }
enum PrinterState { Idle, Active, Aborted, Error }
enum Unit { Millimeter, Point, Inch, Pica, Didot, …, DevicePixel }

Public Functions

QPrinter(const QPrinterInfo &printer, QPrinter::PrinterMode mode = ScreenResolution)
QPrinter(QPrinter::PrinterMode mode = ScreenResolution)
virtual ~QPrinter()
bool abort()
bool collateCopies() const
QPrinter::ColorMode colorMode() const
int copyCount() const
QString creator() const
QString docName() const
QPrinter::DuplexMode duplex() const
bool fontEmbeddingEnabled() const
int fromPage() const
bool fullPage() const
bool isValid() const
QString outputFileName() const
QPrinter::OutputFormat outputFormat() const
QPrinter::PageOrder pageOrder() const
QRectF pageRect(QPrinter::Unit unit) const
QRectF paperRect(QPrinter::Unit unit) const
QPrinter::PaperSource paperSource() const
QPagedPaintDevice::PdfVersion pdfVersion() const
QPrintEngine *printEngine() const
QString printProgram() const
QPrinter::PrintRange printRange() const
QString printerName() const
QString printerSelectionOption() const
QPrinter::PrinterState printerState() const
int resolution() const
void setCollateCopies(bool collate)
void setColorMode(QPrinter::ColorMode newColorMode)
void setCopyCount(int count)
void setCreator(const QString &creator)
void setDocName(const QString &name)
void setDuplex(QPrinter::DuplexMode duplex)
void setFontEmbeddingEnabled(bool enable)
void setFromTo(int from, int to)
void setFullPage(bool fp)
void setOutputFileName(const QString &fileName)
void setOutputFormat(QPrinter::OutputFormat format)
void setPageOrder(QPrinter::PageOrder pageOrder)
void setPaperSource(QPrinter::PaperSource source)
void setPdfVersion(QPagedPaintDevice::PdfVersion version)
void setPrintProgram(const QString &printProg)
void setPrintRange(QPrinter::PrintRange range)
void setPrinterName(const QString &name)
void setPrinterSelectionOption(const QString &option)
void setResolution(int dpi)
QList<QPrinter::PaperSource> supportedPaperSources() const
QList<int> supportedResolutions() const
bool supportsMultipleCopies() const
int toPage() const

Reimplemented Public Functions

virtual bool newPage() override
virtual QPaintEngine *paintEngine() const override

Protected Functions

void setEngines(QPrintEngine *printEngine, QPaintEngine *paintEngine)

Detailed Description

This device represents a series of pages of printed output, and is used in almost exactly the same way as other paint devices such as QWidget and QPixmap. A set of additional functions are provided to manage device-specific features, such as orientation and resolution, and to step through the pages in a document as it is generated.

When printing directly to a printer on Windows or macOS, QPrinter uses the built-in printer drivers. On X11, QPrinter uses the Common Unix Printing System (CUPS) to send PDF output to the printer. As an alternative, the printProgram() function can be used to specify the command or utility to use instead of the system default.

Note that setting parameters like paper size and resolution on an invalid printer is undefined. You can use QPrinter::isValid() to verify this before changing any parameters.

QPrinter supports a number of parameters, most of which can be changed by the end user through a print dialog. In general, QPrinter passes these functions onto the underlying QPrintEngine.

The most important parameters are:

  • setPageLayout() tells QPrinter which page orientation to use, and what size to expect from the printer.
  • setResolution() tells QPrinter what resolution you wish the printer to provide, in dots per inch (DPI).
  • setFullPage() tells QPrinter whether you want to deal with the full page or just with the part the printer can draw on.
  • setCopyCount() tells QPrinter how many copies of the document it should print.

Many of these functions can only be called before the actual printing begins (i.e., before QPainter::begin() is called). This usually makes sense because, for example, it's not possible to change the number of copies when you are halfway through printing. There are also some settings that the user sets (through the printer dialog) and that applications are expected to obey. See QAbstractPrintDialog's documentation for more details.

When QPainter::begin() is called, the QPrinter it operates on is prepared for a new page, enabling the QPainter to be used immediately to paint the first page in a document. Once the first page has been painted, newPage() can be called to request a new blank page to paint on, or QPainter::end() can be called to finish printing. The second page and all following pages are prepared using a call to newPage() before they are painted.

The first page in a document does not need to be preceded by a call to newPage(). You only need to calling newPage() after QPainter::begin() if you need to insert a blank page at the beginning of a printed document. Similarly, calling newPage() after the last page in a document is painted will result in a trailing blank page appended to the end of the printed document.

If you want to abort the print job, abort() will try its best to stop printing. It may cancel the entire job or just part of it.

Since QPrinter can print to any QPrintEngine subclass, it is possible to extend printing support to cover new types of printing subsystem by subclassing QPrintEngine and reimplementing its interface.

See also QPrintDialog and Qt Print Support.

Member Type Documentation

enum QPrinter::ColorMode

This enum type is used to indicate whether QPrinter should print in color or not.

QPrinter::Color1print in color if available, otherwise in grayscale.
QPrinter::GrayScale0print in grayscale, even on color printers.

enum QPrinter::DuplexMode

This enum is used to indicate whether printing will occur on one or both sides of each sheet of paper (simplex or duplex printing).

QPrinter::DuplexNone0Single sided (simplex) printing only.
QPrinter::DuplexAuto1The printer's default setting is used to determine whether duplex printing is used.
QPrinter::DuplexLongSide2Both sides of each sheet of paper are used for printing. The paper is turned over its longest edge before the second side is printed
QPrinter::DuplexShortSide3Both sides of each sheet of paper are used for printing. The paper is turned over its shortest edge before the second side is printed

enum QPrinter::OutputFormat

The OutputFormat enum is used to describe the format QPrinter should use for printing.

QPrinter::NativeFormat0QPrinter will print output using a method defined by the platform it is running on. This mode is the default when printing directly to a printer.
QPrinter::PdfFormat1QPrinter will generate its output as a searchable PDF file. This mode is the default when printing to a file.

See also outputFormat(), setOutputFormat(), and setOutputFileName().

enum QPrinter::PageOrder

This enum type is used by QPrinter to tell the application program how to print.

QPrinter::FirstPageFirst0the lowest-numbered page should be printed first.
QPrinter::LastPageFirst1the highest-numbered page should be printed first.

enum QPrinter::PaperSource

This enum type specifies what paper source QPrinter is to use. QPrinter does not check that the paper source is available; it just uses this information to try and set the paper source. Whether it will set the paper source depends on whether the printer has that particular source.

Warning: This is currently only implemented for Windows.

QPrinter::MaxPageSource13Deprecated, use LastPaperSource instead
QPrinter::CustomSource14A PaperSource defined by the printer that is unknown to Qt
QPrinter::LastPaperSourceCustomSourceThe highest valid PaperSource value, currently CustomSource

enum QPrinter::PrintRange

Used to specify the print range selection option.

QPrinter::AllPages0All pages should be printed.
QPrinter::Selection1Only the selection should be printed.
QPrinter::PageRange2The specified page range should be printed.
QPrinter::CurrentPage3Only the current page should be printed.

See also setPrintRange(), printRange(), and QAbstractPrintDialog::PrintRange.

enum QPrinter::PrinterMode

This enum describes the mode the printer should work in. It basically presets a certain resolution and working mode.

QPrinter::ScreenResolution0Sets the resolution of the print device to the screen resolution. This has the big advantage that the results obtained when painting on the printer will match more or less exactly the visible output on the screen. It is the easiest to use, as font metrics on the screen and on the printer are the same. This is the default value. ScreenResolution will produce a lower quality output than HighResolution and should only be used for drafts.
QPrinter::PrinterResolution1This value is deprecated. It is equivalent to ScreenResolution on Unix and HighResolution on Windows and Mac. Due to the difference between ScreenResolution and HighResolution, use of this value may lead to non-portable printer code.
QPrinter::HighResolution2On Windows, sets the printer resolution to that defined for the printer in use. For PDF printing, sets the resolution of the PDF driver to 1200 dpi.

Note: When rendering text on a QPrinter device, it is important to realize that the size of text, when specified in points, is independent of the resolution specified for the device itself. Therefore, it may be useful to specify the font size in pixels when combining text with graphics to ensure that their relative sizes are what you expect.

enum QPrinter::PrinterState


enum QPrinter::Unit

This enum type is used to specify the measurement unit for page and paper sizes.


Note the difference between Point and DevicePixel. The Point unit is defined to be 1/72th of an inch, while the DevicePixel unit is resolution dependant and is based on the actual pixels, or dots, on the printer.

Member Function Documentation

QPrinter::QPrinter(const QPrinterInfo &printer, QPrinter::PrinterMode mode = ScreenResolution)

Creates a new printer object with the given printer and mode.

QPrinter::QPrinter(QPrinter::PrinterMode mode = ScreenResolution)

Creates a new printer object with the given mode.

[virtual] QPrinter::~QPrinter()

Destroys the printer object and frees any allocated resources. If the printer is destroyed while a print job is in progress this may or may not affect the print job.

bool QPrinter::abort()

Aborts the current print run. Returns true if the print run was successfully aborted and printerState() will return QPrinter::Aborted; otherwise returns false.

It is not always possible to abort a print job. For example, all the data has gone to the printer but the printer cannot or will not cancel the job when asked to.

bool QPrinter::collateCopies() const

Returns true if collation is turned on when multiple copies is selected. Returns false if it is turned off when multiple copies is selected. When collating is turned off the printing of each individual page will be repeated the numCopies() amount before the next page is started. With collating turned on all pages are printed before the next copy of those pages is started.

See also setCollateCopies().

QPrinter::ColorMode QPrinter::colorMode() const

Returns the current color mode.

See also setColorMode().

int QPrinter::copyCount() const

Returns the number of copies that will be printed. The default value is 1.

See also setCopyCount() and supportsMultipleCopies().

QString QPrinter::creator() const

Returns the name of the application that created the document.

See also setCreator().

QString QPrinter::docName() const

Returns the document name.

See also setDocName() and QPrintEngine::PrintEnginePropertyKey.

QPrinter::DuplexMode QPrinter::duplex() const

Returns the current duplex mode.

See also setDuplex().

bool QPrinter::fontEmbeddingEnabled() const

Returns true if font embedding is enabled.

See also setFontEmbeddingEnabled().

int QPrinter::fromPage() const

Returns the number of the first page in a range of pages to be printed (the "from page" setting). Pages in a document are numbered according to the convention that the first page is page 1.

By default, this function returns a special value of 0, meaning that the "from page" setting is unset.

Note: If fromPage() and toPage() both return 0, this indicates that the whole document will be printed.

See also setFromTo(), toPage(), and pageRanges().

bool QPrinter::fullPage() const

Returns true if the origin of the printer's coordinate system is at the corner of the page and false if it is at the edge of the printable area.

See setFullPage() for details and caveats.

See also setFullPage() and QPagedPaintDevice::pageLayout().

bool QPrinter::isValid() const

Returns true if the printer currently selected is a valid printer in the system, or a pure PDF printer; otherwise returns false.

To detect other failures check the output of QPainter::begin() or QPrinter::newPage().

    QPrinter printer;
    QPainter painter;
    if (! painter.begin(&printer)) { // failed to open file
        qWarning("failed to open file, is it writable?");
        return 1;
    painter.drawText(10, 10, "Test");
    if (! printer.newPage()) {
        qWarning("failed in flushing page to disk, disk full?");
        return 1;
    painter.drawText(10, 10, "Test 2");

See also setPrinterName().

[override virtual] bool QPrinter::newPage()

Reimplements: QPagedPaintDevice::newPage().

Tells the printer to eject the current page and to continue printing on a new page. Returns true if this was successful; otherwise returns false.

Calling newPage() on an inactive QPrinter object will always fail.

QString QPrinter::outputFileName() const

Returns the name of the output file. By default, this is an empty string (indicating that the printer shouldn't print to file).

See also setOutputFileName() and QPrintEngine::PrintEnginePropertyKey.

QPrinter::OutputFormat QPrinter::outputFormat() const

Returns the output format for this printer.

See also setOutputFormat().

QPrinter::PageOrder QPrinter::pageOrder() const

Returns the current page order.

The default page order is FirstPageFirst.

See also setPageOrder().

QRectF QPrinter::pageRect(QPrinter::Unit unit) const

Returns the page's rectangle in unit; this is usually smaller than the paperRect() since the page normally has margins between its borders and the paper.

See also QPagedPaintDevice::pageLayout().

[override virtual] QPaintEngine *QPrinter::paintEngine() const

Reimplements: QPaintDevice::paintEngine() const.

Returns the paint engine used by the printer.

QRectF QPrinter::paperRect(QPrinter::Unit unit) const

Returns the paper's rectangle in unit; this is usually larger than the pageRect().

See also pageRect().

QPrinter::PaperSource QPrinter::paperSource() const

Returns the printer's paper source. This is Manual or a printer tray or paper cassette.

See also setPaperSource().

[since 5.10] QPagedPaintDevice::PdfVersion QPrinter::pdfVersion() const

Returns the PDF version for this printer. The default is PdfVersion_1_4.

This function was introduced in Qt 5.10.

See also setPdfVersion().

QPrintEngine *QPrinter::printEngine() const

Returns the print engine used by the printer.

QString QPrinter::printProgram() const

Returns the name of the program that sends the print output to the printer.

The default is to return an empty string; meaning that QPrinter will try to be smart in a system-dependent way. On X11 only, you can set it to something different to use a specific print program. On the other platforms, this returns an empty string.

See also setPrintProgram() and setPrinterSelectionOption().

QPrinter::PrintRange QPrinter::printRange() const

Returns the page range of the QPrinter. After the print setup dialog has been opened, this function returns the value selected by the user.

See also setPrintRange().

QString QPrinter::printerName() const

Returns the printer name. This value is initially set to the name of the default printer.

See also setPrinterName().

QString QPrinter::printerSelectionOption() const

Returns the printer options selection string. This is useful only if the print command has been explicitly set.

The default value (an empty string) implies that the printer should be selected in a system-dependent manner.

Any other value implies that the given value should be used.

This function always returns an empty string on Windows and Mac.

See also setPrinterSelectionOption() and setPrintProgram().

QPrinter::PrinterState QPrinter::printerState() const

Returns the current state of the printer. This may not always be accurate (for example if the printer doesn't have the capability of reporting its state to the operating system).

int QPrinter::resolution() const

Returns the current assumed resolution of the printer, as set by setResolution() or by the printer driver.

See also setResolution().

void QPrinter::setCollateCopies(bool collate)

Sets the default value for collation checkbox when the print dialog appears. If collate is true, it will enable setCollateCopiesEnabled(). The default value is false. This value will be changed by what the user presses in the print dialog.

See also collateCopies().

void QPrinter::setColorMode(QPrinter::ColorMode newColorMode)

Sets the printer's color mode to newColorMode, which can be either Color or GrayScale.

See also colorMode().

void QPrinter::setCopyCount(int count)

Sets the number of copies to be printed to count.

The printer driver reads this setting and prints the specified number of copies.

See also copyCount() and supportsMultipleCopies().

void QPrinter::setCreator(const QString &creator)

Sets the name of the application that created the document to creator.

This function is only applicable to the X11 version of Qt. If no creator name is specified, the creator will be set to "Qt" followed by some version number.

See also creator().

void QPrinter::setDocName(const QString &name)

Sets the document name to name.

On X11, the document name is for example used as the default output filename in QPrintDialog. Note that the document name does not affect the file name if the printer is printing to a file. Use the setOutputFile() function for this.

See also docName() and QPrintEngine::PrintEnginePropertyKey.

void QPrinter::setDuplex(QPrinter::DuplexMode duplex)

Enables double sided printing based on the duplex mode.

See also duplex().

[protected] void QPrinter::setEngines(QPrintEngine *printEngine, QPaintEngine *paintEngine)

This function is used by subclasses of QPrinter to specify custom print and paint engines (printEngine and paintEngine, respectively).

QPrinter does not take ownership of the engines, so you need to manage these engine instances yourself.

Note that changing the engines will reset the printer state and all its properties.

See also printEngine(), paintEngine(), and setOutputFormat().

void QPrinter::setFontEmbeddingEnabled(bool enable)

Enabled or disables font embedding depending on enable.

See also fontEmbeddingEnabled().

void QPrinter::setFromTo(int from, int to)

Sets the range of pages to be printed to cover the pages with numbers specified by from and to, where from corresponds to the first page in the range and to corresponds to the last.

Note: Pages in a document are numbered according to the convention that the first page is page 1. However, if from and to are both set to 0, the whole document will be printed.

This function is mostly used to set a default value that the user can override in the print dialog when you call setup().

See also fromPage(), toPage(), and pageRanges().

void QPrinter::setFullPage(bool fp)

If fp is true, enables support for painting over the entire page; otherwise restricts painting to the printable area reported by the device.

By default, full page printing is disabled. In this case, the origin of the QPrinter's coordinate system coincides with the top-left corner of the printable area.

If full page printing is enabled, the origin of the QPrinter's coordinate system coincides with the top-left corner of the paper itself. In this case, the device metrics will report the exact same dimensions as indicated by {QPageSize}. It may not be possible to print on the entire physical page because of the printer's margins, so the application must account for the margins itself.

See also fullPage(), QPagedPaintDevice::pageLayout(), and QPagedPaintDevice::setPageSize().

void QPrinter::setOutputFileName(const QString &fileName)

Sets the name of the output file to fileName.

Setting a null or empty name (0 or "") disables printing to a file. Setting a non-empty name enables printing to a file.

This can change the value of outputFormat(). If the file name has the ".pdf" suffix PDF is generated. If the file name has a suffix other than ".pdf", the output format used is the one set with setOutputFormat().

QPrinter uses Qt's cross-platform PDF print engines respectively. If you can produce this format natively, for example macOS can generate PDF's from its print engine, set the output format back to NativeFormat.

See also outputFileName() and setOutputFormat().

void QPrinter::setOutputFormat(QPrinter::OutputFormat format)

Sets the output format for this printer to format.

If format is the same value as currently set then no change will be made.

If format is NativeFormat then the printerName will be set to the default printer. If there are no valid printers configured then no change will be made. If you want to set NativeFormat with a specific printerName then use setPrinterName().

See also outputFormat() and setPrinterName().

void QPrinter::setPageOrder(QPrinter::PageOrder pageOrder)

Sets the page order to pageOrder.

The page order can be QPrinter::FirstPageFirst or QPrinter::LastPageFirst. The application is responsible for reading the page order and printing accordingly.

This function is mostly useful for setting a default value that the user can override in the print dialog.

This function is only supported under X11.

See also pageOrder().

void QPrinter::setPaperSource(QPrinter::PaperSource source)

Sets the paper source setting to source.

Windows only: This option can be changed while printing and will take effect from the next call to newPage()

See also paperSource().

[since 5.10] void QPrinter::setPdfVersion(QPagedPaintDevice::PdfVersion version)

Sets the PDF version for this printer to version.

If version is the same value as currently set then no change will be made.

This function was introduced in Qt 5.10.

See also pdfVersion().

void QPrinter::setPrintProgram(const QString &printProg)

Sets the name of the program that should do the print job to printProg.

On X11, this function sets the program to call with the PDF output. On other platforms, it has no effect.

See also printProgram().

void QPrinter::setPrintRange(QPrinter::PrintRange range)

Sets the print range option in to be range.

See also printRange().

void QPrinter::setPrinterName(const QString &name)

Sets the printer name to name.

If the name is empty then the output format will be set to PdfFormat.

If the name is not a valid printer then no change will be made.

If the name is a valid printer then the output format will be set to NativeFormat.

See also printerName(), isValid(), and setOutputFormat().

void QPrinter::setPrinterSelectionOption(const QString &option)

Sets the printer to use option to select the printer. option is null by default (which implies that Qt should be smart enough to guess correctly), but it can be set to other values to use a specific printer selection option.

If the printer selection option is changed while the printer is active, the current print job may or may not be affected.

This function has no effect on Windows or Mac.

See also printerSelectionOption() and setPrintProgram().

void QPrinter::setResolution(int dpi)

Requests that the printer prints at dpi or as near to dpi as possible.

This setting affects the coordinate system as returned by, for example QPainter::viewport().

This function must be called before QPainter::begin() to have an effect on all platforms.

See also resolution() and QPagedPaintDevice::setPageSize().

QList<QPrinter::PaperSource> QPrinter::supportedPaperSources() const

Returns the supported paper sizes for this printer.

The values will be either a value that matches an entry in the QPrinter::PaperSource enum or a driver spesific value. The driver spesific values are greater than the constant DMBIN_USER declared in wingdi.h.

Warning: This function is only available in windows.

QList<int> QPrinter::supportedResolutions() const

Returns a list of the resolutions (a list of dots-per-inch integers) that the printer says it supports.

For X11 where all printing is directly to PDF, this function will always return a one item list containing only the PDF resolution, i.e., 72 (72 dpi -- but see PrinterMode).

bool QPrinter::supportsMultipleCopies() const

Returns true if the printer supports printing multiple copies of the same document in one job; otherwise false is returned.

On most systems this function will return true. However, on X11 systems that do not support CUPS, this function will return false. That means the application has to handle the number of copies by printing the same document the required number of times.

See also setCopyCount() and copyCount().

int QPrinter::toPage() const

Returns the number of the last page in a range of pages to be printed (the "to page" setting). Pages in a document are numbered according to the convention that the first page is page 1.

By default, this function returns a special value of 0, meaning that the "to page" setting is unset.

Note: If fromPage() and toPage() both return 0, this indicates that the whole document will be printed.

The programmer is responsible for reading this setting and printing accordingly.

See also setFromTo(), fromPage(), and pageRanges().

© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.