同一QPainter中为不同文本变量设置不同字体的实现方法
Can I use the same QPainter instance for texts with different fonts?
Short answer: Absolutely! But your current approach of concatenating both texts and drawing them in one go won’t get you the result you want—since the painter’s active font applies to the entire drawText call. Here’s how to fix this while keeping the same QPainter instance:
Step-by-step solution
- Stick with your single QPainter instance (no need to create new ones).
- Draw each text separately, updating the painter’s font between calls.
- For text2, create a modified copy of your
boldUnderlinefont that retains the bold/underline styles but uses the Arial family.
Example code
# Assume your original boldUnderline font is defined like this boldUnderline = QFont() boldUnderline.setBold(True) boldUnderline.setUnderline(True) # Create an Arial version of the boldUnderline font (retains all styles except family) arialBoldUnderline = QFont(boldUnderline) # Copy existing font properties arialBoldUnderline.setFamily("Arial") # Initialize your painter painter = QtGui.QPainter() # Draw text1 with the original boldUnderline font painter.setFont(boldUnderline) text1_content = self.text1.text() painter.drawText(80, 290, text1_content) # Calculate where text2 should start (right after text1, with a small gap) text1_bounds = painter.boundingRect(80, 290, 0, 0, Qt.TextSingleLine, text1_content) text2_x_position = text1_bounds.right() + 5 # Add 5px spacing between texts # Draw text2 with the Arial bold/underline font painter.setFont(arialBoldUnderline) painter.drawText(text2_x_position, 290, self.text2.text())
Key details
- When you copy
boldUnderlineto createarialBoldUnderline, it inherits all existing properties (bold, underline, font size, etc.)—you only need to override the family. - Using
boundingRectensures text2 lines up perfectly after text1, just like your original concatenated approach would have. - You can switch fonts as many times as needed with the same painter instance—just call
setFont()before eachdrawText()call.
This method keeps your code clean, uses a single painter, and gives you precise control over each text’s styling.
内容的提问来源于stack exchange,提问作者koki
相关产品推荐
相关产品推荐

