简体   繁体   English

PyQt:使用QPrinter中的drawText将QPainter文本居中

[英]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 我正在尝试将文本集中在正常的A4尺寸的作品集中,获得的尺寸是正确的,但是它没有居中,并且我不知道原因是什么,在这里我向您展示代码

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使用不同类型的度量单位

QPrinter.Unit 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: 当您通过paperSize()方法获得尺寸时,您会以QPrinter.Point单位要求它的大小,但是QPainter使用以像素为单位的坐标(即QPrinter.DevicePixel来求解,因此获得的宽度不同于以像素为单位的宽度如果我们仅更改度量单位的类型,如下所示:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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