我不知道它是否可能选择不同的文本字体为每个变量在同一画家。
painter.drawText(80, 290, self.text1.text() + self.text2.text())
这是一个例子:对于
下面是完整的代码:
underlineItalic = QFont()
underlineItalic.setItalic(True)
underlineItalic.setUnderline(True)
painter = QtGui.QPainter()
painter.setFont(boldUnderline)
painter.drawText(80, 290, self.text1.text() + self.text2.text())
在这种方式上有没有选择做这件事?如果这条路不行,还有别的路吗?
要执行此任务,您可以使用
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")