qt - Qt在boundingRect中包装文本
问题描述
我正在用 PyQt 编写一个应用程序,我需要包装我正在绘制的文本。我使用类的boundingRect
方法QFontMetrics
来定义大小然后QPainter.drawText
进行绘制。我需要文本适合给定的矩形。这是我使用的行:
rect = metrics.boundingRect(rect, Qt.TextWordWrap, text)
但是,由于 flag Qt.TextWordWrap
,如果文本没有任何空格,则它不会换行并且不适合矩形。我试过Qt.TextWrapAnywhere
了,但即使有空格,这也会把单词分开。Qt.TextFlag
似乎没有任何标志,优先考虑包装单词,并且只有在不可能的情况下才会将单词分开,例如QTextOption.WrapAtWordBoundaryOrAnywhere
. 有没有办法使用boundingRect
and来包装这样的文本drawText
?
解决方案
对于这样的情况,通常最好使用 QTextDocument,它允许使用更高级的选项。
class WrapAnywhereLabel(QtWidgets.QWidget):
def __init__(self, text=''):
super().__init__()
self.doc = QtGui.QTextDocument(text)
self.doc.setDocumentMargin(0)
opt = QtGui.QTextOption()
opt.setWrapMode(opt.WrapAtWordBoundaryOrAnywhere)
self.doc.setDefaultTextOption(opt)
def hasHeightForWidth(self):
return True
def heightForWidth(self, width):
self.doc.setTextWidth(width)
return self.doc.size().height()
def sizeHint(self):
return self.doc.size().toSize()
def resizeEvent(self, event):
self.doc.setTextWidth(self.width())
def paintEvent(self, event):
qp = QtGui.QPainter(self)
self.doc.drawContents(qp, QtCore.QRectF(self.rect()))
import sys
app = QtWidgets.QApplication(sys.argv)
w = WrapAnywhereLabel('hellooooo hello hellooooooooooooooo')
w.show()
sys.exit(app.exec_())
推荐阅读
- c# - 使用更多构造函数从另一个类访问主类
- flutter - 如何像 Kotlin 一样根据 Dart 中的 if 语句声明变量?
- javascript - 对 RPG 的深刻 UI ajax 请求
- amazon-web-services - AWS EC2 实例存储在重启后消失
- r - 使用气候数据运算符转换的 netcdf 中的日期错误
- amazon-web-services - 有没有办法从 AWS CodePIPELINE 控制保存在 S3 中的构建工件名称
- swift - 在 macOS 的 swift 5 中声明 ExtAudioFileRef 的正确方法
- ios - ios kSecClassCertificate 产生 -25303
- javascript - 如何将谷歌图表中的图表颜色作为事件更改?
- php - 从 Firebase 存储 (PHP) 获取 URL