I dont know if its possible to chose different text font for each variable inside the same painter.
painter.drawText(80, 290, self.text1.text() + self.text2.text())
This is the example: for text1
want to leave it default as I set in the painter (boldUnderline
) while text2
will have (boldUnderline
) but also I want to change the text font to another one lets say Arial the point is to be different from text1
because its supposed to be in different language
Here is the full code:
underlineItalic = QFont()
underlineItalic.setItalic(True)
underlineItalic.setUnderline(True)
painter = QtGui.QPainter()
painter.setFont(boldUnderline)
painter.drawText(80, 290, self.text1.text() + self.text2.text())
Is there any option to do this on this way? If it can not be this way is there any other way?
To perform this task you can use QTextDocument
, to set the format we use QTextCharFormat()
where you must set a font.
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)
Example:
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")
Output:
You can also use html in QTextDocument:
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")