简体   繁体   中英

PyQt: Center QPainter text with drawText in QPrinter

I am trying to focus the text on a normal A4 size folio, the sizes obtained are correct but it is not centered and I do not know what the reason is, here I show you the code

from PyQt4.QtGui import QPrinter,QPainter,QApplication
from PyQt4.QtCore import Qt,QRectF
import sys

app = QApplication(sys.argv)

printer = QPrinter()
painter = QPainter()

printer.setOutputFileName("prueba.pdf")
printer.setOutputFormat(QPrinter.PdfFormat)

printer.setPageMargins(0.0,0.0,0.0,0.0,1)
printer.setFullPage(True)
margin = printer.getPageMargins(1)
print margin
size = printer.paperSize(1)
width = size.width()
print width

painter.begin(printer)
painter.drawText(QRectF(0.0,0.0,width,50.0),Qt.AlignCenter|Qt.AlignTop,"abcdefghijklmn")
painter.end()

As you can see I get the width of the size of a folio type point and putting the entire width of the folio does not fit evenly

QPrinter uses different types of units of measure :

QPrinter.Unit

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

 Constant Value QPrinter.Millimeter 0 QPrinter.Point 1 QPrinter.Inch 2 QPrinter.Pica 3 QPrinter.Didot 4 QPrinter.Cicero 5 QPrinter.DevicePixel 6 

When you get the size through the paperSize() method you are asking for it in QPrinter.Point units, but QPainter uses the coordinates in pixels, that is, QPrinter.DevicePixel so the obtained width is different from the width in pixels, to solve that if we just change the type of units of measurement as shown below:

app = QApplication(sys.argv)

printer = QPrinter()
painter = QPainter()

printer.setOutputFileName("prueba.pdf")
printer.setOutputFormat(QPrinter.PdfFormat)

printer.setPageMargins(0.0, 0.0, 0.0, 0.0, QPrinter.Point)
printer.setFullPage(True)
margin = printer.getPageMargins(QPrinter.Point)
print(margin)
size = printer.paperSize(QPrinter.DevicePixel)
width = size.width()
print(width)

painter.begin(printer)
painter.drawText(QRectF(0.0,0.0,width,50.0), Qt.AlignCenter|Qt.AlignTop, "abcdefghijklmn")
painter.end()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM