Printing a file

David Boddie davidb at
Wed Mar 1 18:10:20 CET 2006

Fabian Steiner wrote:

> This is what I have so far:
> app = QApplication(sys.argv)
> printer = QPrinter(QPrinter.PrinterResolution)
> if printer.setup():
>      printer.setPageSize(printer.A4)
>      painter = QPainter(printer)
>      metrics = QPaintDeviceMetrics(painter.device())
>      marginHeight = 6
>      marginWidth =  8
>      body = QRect(marginWidth, marginHeight, metrics.widthMM() - 2 *
> marginWidth, metrics.heightMM() - 2 * marginHeight)
>      painter.drawRect(body)
>      painter.end()
> Doing so I hoped to get a rectangle which is as big as an A4 paper (with
> a small border), but unfortunately it is much smaller.

Surely you meant to use

body = QRect(marginWidth, marginHeight,
             metrics.width() - 2 * marginWidth,
             metrics.height() - 2 * marginHeight)

> Moreover, I ask myself whether it is necessary that in order to write
> text on the paper, I always have to pass the proper x, y values to
> QPainter.drawText().
> Isn't there any other possibility? How do I get these values?

That depends on what kind of text you're drawing (paragraphs of text
vs. simple labels). See the example in the examples3
directory of the PyQt3 distribution for code that implements a simple
text editor with support for printing. Information about text and font
metrics can be found with the QFontMetrics class:

PyQt4 supports Qt 4's new rich text facilities, so it's easier to
format text for printing than it is in Qt 3. A more advanced rich text
editor is only available in the C++ Qt 4 demos, but there are other
examples bundled with PyQt4 that show how to print "simple" documents:

Finally, it's worth pointing out that there's a higher concentration of
people with experience in these matters reading the PyQt/PyKDE mailing

Good luck with your printing,


More information about the Python-list mailing list