要执行此任务,您可以使用QTextDocument
, 来设置我们使用的格式QTextCharFormat()
,您必须在其中设置字体。
doc = QTextDocument()
cursor = QTextCursor(doc)
fm = QTextCharFormat()
font = painter.font()
font.setBold(True)
font.setUnderline(True)
fm.setFont(font) # set QFont
cursor.insertText(text1, fm) # insert text with new format.
# establish new format for example:
# font.setItalic(True)
# font.setBold(True)
cursor.insertText(text1, fm)
painter.translate(80, 290)
doc.drawContents(painter)
例子:
if __name__ == '__main__':
app = QApplication(sys.argv)
img = QImage(640, 480, QImage.Format_RGB32);
img.fill(Qt.white);
text1, text2 ="Stack Overflow".split()
painter = QPainter(img);
doc = QTextDocument()
cursor = QTextCursor(doc)
fm = QTextCharFormat()
font = painter.font()
font.setItalic(True)
font.setUnderline(True)
fm.setFont(font)
cursor.insertText(text1, fm)
font.setItalic(True)
font.setBold(True)
font.setUnderline(False)
fm.setFont(font)
cursor.insertText(text2, fm)
painter.translate(80, 290)
doc.drawContents(painter)
painter.end();
img.save("text.png")
输出:
您还可以在 QTextDocument 中使用 html:
if __name__ == '__main__':
app = QApplication(sys.argv)
img = QImage(640, 480, QImage.Format_RGB32);
img.fill(Qt.white);
text1, text2 ="Stack Overflow".split()
painter = QPainter(img);
doc = QTextDocument()
cursor = QTextCursor(doc)
cursor.insertHtml("<i><u>{first}</u></i><b><i>{second}<b></i>".format(first=text1, second=text2))
painter.translate(80, 290)
doc.drawContents(painter)
painter.end();
img.save("text.png")