要在QPainter中绘制自动换行的文本,您可以使用QFontMetrics来确定文本的宽度,并根据宽度将文本分为多行。以下是一个示例代码:

from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPainter, QFontMetrics, QFont
from PyQt5.QtCore import Qt

class Example(QWidget):
    def __init__(self):
        super().__init__()
        
        self.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        
        self.resize(300, 200)
        self.setWindowTitle("Text Wrapping Example")
        
    def paintEvent(self, event):
        painter = QPainter(self)
        
        # 设置字体和对齐方式
        font = QFont("Arial", 12)
        painter.setFont(font)
        painter.setPen(Qt.black)
        
        # 获取字体测量对象
        fm = QFontMetrics(font)
        
        # 将文本分为多行
        lines = []
        current_line = ""
        for word in self.text.split():
            if fm.width(current_line + " " + word) <= self.width():
                current_line += " " + word
            else:
                lines.append(current_line)
                current_line = word
        lines.append(current_line)
        
        # 绘制每一行文本
        y = 0
        for line in lines:
            y += fm.height()
            painter.drawText(0, y, line)
        
if __name__ == '__main__':
    app = QApplication([])
    ex = Example()
    ex.show()
    app.exec_()

在这个示例中,我们首先将要绘制的文本存储在self.text变量中。然后,在绘制事件的处理方法paintEvent中,我们设置了字体和对齐方式,并使用QFontMetrics获取字体的测量对象。接下来,我们将文本分为多行。我们使用一个current_line变量来存储当前行的文本,如果将当前单词添加到current_line后,它的宽度不超过窗口的宽度,就将其添加到current_line中。否则,我们将current_line添加到lines列表中,并将current_line重置为当前单词。最后,我们使用QPainter的drawText方法绘制每一行的文本。

请注意,这只是一个简单的示例,如果您的需求更复杂,您可能需要考虑更多的文本处理方式,比如处理超出窗口高度的情况,以及更复杂的对齐方式

QPainter绘制文本自动分行

原文地址: https://www.cveoy.top/t/topic/ieJc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录