You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同一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

  1. Stick with your single QPainter instance (no need to create new ones).
  2. Draw each text separately, updating the painter’s font between calls.
  3. For text2, create a modified copy of your boldUnderline font 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 boldUnderline to create arialBoldUnderline, it inherits all existing properties (bold, underline, font size, etc.)—you only need to override the family.
  • Using boundingRect ensures 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 each drawText() call.

This method keeps your code clean, uses a single painter, and gives you precise control over each text’s styling.

内容的提问来源于stack exchange,提问作者koki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:56:09