PyQt:使用QPrinter中的drawText中心QPainter文本

时间:2017-09-19 14:11:20

标签: python pyqt pyqt4 qpainter qprinter

我正在尝试将文本集中在普通的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()

正如您所看到的,我得到了对开式点的大小宽度,并且对开页的整个宽度不均匀

1 个答案:

答案 0 :(得分:0)

QPrinter使用不同类型的units of measure

  

<强> QPrinter.Unit

     

此枚举类型用于指定页面和纸张尺寸的测量单位。

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

当您通过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() 获得的宽度不同于宽度(以像素为单位),以解决如果我们只改变测量单位的类型,如下所示:

var = {'hello': 'world', 'good': 'day', 'see': 'you'}