Qpainter draw text 自动换行
时间: 2023-12-15 15:07:17 浏览: 289
要在QPainter中实现自动换行功能,可以使用QFontMetrics类来计算文本的宽度和高度,然后根据所需的宽度和高度进行换行。以下是一个简单的示例代码:
```python
from PyQt5.QtGui import QPainter, QFontMetrics
from PyQt5.QtCore import Qt
# ...
def paintEvent(self, event):
painter = QPainter(self)
font = painter.font()
font.setPointSize(14)
painter.setFont(font)
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Sed eget mi nec mi porta dictum. Aliquam erat volutpat. Donec eleifend nulla eget nulla malesuada convallis. Sed quis diam eget dolor auctor aliquam ut eget eros. Sed eget neque porttitor, cursus nulla facilisis, gravida lectus. Sed vel pharetra purus. Sed in sollicitudin mi, id interdum velit. Vivamus gravida dapibus dolor, nec facilisis lacus imperdiet eget. Maecenas sed turpis sed velit iaculis bibendum. Duis feugiat augue in sodales pulvinar. In non mi euismod, laoreet nibh sit amet, vestibulum sapien. Fusce ac tristique turpis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed in nulla id neque consequat ultricies. Nulla facilisi."
rect = self.geometry()
top_margin = 20
bottom_margin = 20
left_margin = 20
right_margin = 20
fm = QFontMetrics(font)
y = top_margin
for line in text.split('\n'):
x = left_margin
for word in line.split():
word_width = fm.width(word)
if x + word_width > rect.width() - right_margin:
x = left_margin
y += fm.height()
painter.drawText(x, y, word)
x += word_width + fm.width(' ')
y += fm.height()
painter.end()
```
在此示例中,我们首先设置了字体大小为14,并将其应用于绘图器。然后,我们定义了要绘制的多行文本。接下来,我们定义了绘制区域的边距,并使用QFontMetrics类计算每个单词的宽度和高度。最后,我们使用嵌套的循环来逐个单词地绘制文本,并在达到绘制区域的右侧时换行。
请注意,此示例仅处理空格分隔的单词,而不考虑其他标点符号。要处理其他标点符号,需要对代码进行修改。
阅读全文