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

PySide6中QPainter.drawText()实现文本自动换行问题求助

解决QPainter.drawText自动换行+居中对齐的崩溃问题

你崩溃的核心原因是参数类型不匹配:Qt.AlignmentFlag.AlignCenter是对齐枚举值,而QTextOption.WrapMode.WordWrap属于文本选项的换行模式,两者不能直接用|组合传递给drawText的第二个参数(该参数仅接受对齐标志)。

正确的做法是通过QTextOption对象统一配置对齐和换行规则,调用对应的drawText重载方法:

修改你的代码如下:

rectangle = QRect(self.startX, self.startY, int(self.Width), int(self.Length))
painter.fillRect(rectangle, self.colorList[i])

# 创建文本选项,同时设置居中对齐和单词换行
text_option = QTextOption()
text_option.setAlignment(Qt.AlignmentFlag.AlignCenter)
text_option.setWrapMode(QTextOption.WrapMode.WordWrap)

# 使用带QTextOption的drawText重载
painter.drawText(rectangle, self.AssiName[i], text_option)

painter.drawRect(rectangle)

这个版本调用的是QPainter.drawText(const QRect &rect, const QString &text, const QTextOption &option)重载,能正确解析文本选项中的换行和对齐设置,避免类型不匹配导致的崩溃,同时实现文本超出矩形时自动按单词换行、整体居中的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:13:12