Qt4/PyQt4 - Can not set the default font for QTextDocument

谁都会走 提交于 2021-01-28 18:41:49

问题


My code is like this:

from PyQt4 import QtGui

doc = QtGui.QTextDocument()
d_font = QtGui.QFont('Times New Roman')
doc.setDefaultFont(d_font)

cur = QtGui.QTextCursor(doc)
cur.insertText('sample text')

writer = QtGui.QTextDocumentWriter()
writer.setFormat(writer.supportedDocumentFormats()[1])
writer.setFileName('CV')
writer.write(doc)

The 'sample text' in the output is still 'Sans' on my computer rather than "Times New Roman'. I have made sure my computer has 'Times New Roman' font. I suspect this is a bug. I'm using PyQt v4.9.5.

EDIT: I'm using Ubuntu 12.04. I'm quite sure that PyQt4 can find the font, because the following code works:

d_font = QFont('Times New Roman')
char_fmt = QTextCharFormat()
char_fmt.setFont(d_font)
cur.insertText('Times New Roman', char_fmt)

It appears that not all formating is supported when saving in odt/odt format, but everything works as expected when printing to a pdf.

from PyQt4.QtGui import *
import sys

doc = QTextDocument()
cur = QTextCursor(doc)

d_font = QFont('Times New Roman')
doc.setDefaultFont(d_font)

table_fmt = QTextTableFormat()
table_fmt.setColumnWidthConstraints([
    QTextLength(QTextLength.PercentageLength, 30),
    QTextLength(QTextLength.PercentageLength, 70)
    ])
table = cur.insertTable(5,2, table_fmt)
cur.insertText('sample text 1')
cur.movePosition(cur.NextCell)
cur.insertText('sample text 2')

# Print to a pdf file
# QPrinter: Must construct a QApplication before a QPaintDevice
app = QApplication(sys.argv)
printer = QPrinter(QPrinter.HighResolution)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName('sample.pdf')

# Save to file
writer = QTextDocumentWriter()
writer.setFormat(writer.supportedDocumentFormats()[1])
writer.setFileName('sample.odt')
writer.write(doc)

setDefaultfonts and setColumnWidthConstraints affect sample.pdf, but not sample.odt.


回答1:


I can see the same behavior on my Ubuntu Oneiric box with PyQt4.8.5. I don't think it is a bug. The font of the written text depends on the font of the cursor used to write the text.

The following should work for you:

from PyQt4 import QtGui

doc = QtGui.QTextDocument()
cur = QtGui.QTextCursor(doc)

d_font = QtGui.QFont('Courier')
c_format = QtGui.QTextCharFormat()
c_format.setFont(d_font)
cur.setCharFormat(c_format)
cur.insertText('sample text')

writer = QtGui.QTextDocumentWriter()
writer.setFormat(writer.supportedDocumentFormats()[1])
writer.setFileName('CV')
writer.write(doc)

I've used Courier because Times New Roman is not installed on my system.



来源:https://stackoverflow.com/questions/12767147/qt4-pyqt4-can-not-set-the-default-font-for-qtextdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!