简体   繁体   中英

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

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.

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.

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