pythonpyqtpysideword-wrapqtextedit

Indent while line wrap on QTextEdit with PySide6 / PyQt6


I'm looking to have an indent every time a line is wrapping in a QTextEdit. My goal is to be able to differentiate a new line from a line wrap easily.

I tried to look at QTextBlockFormat, found a way to have an indent every new line, so the invert of what I want to produce.

Here the test code for that:

import sys
from PySide6.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout
from PySide6.QtGui import QTextCursor, QTextBlockFormat

class Widget(QWidget):
    def __init__(self):
        super().__init__()
        self.text_edit = QTextEdit()
        v_layout = QVBoxLayout()
        v_layout.addWidget(self.text_edit)
        self.setLayout(v_layout)

        self.text_edit.setPlainText(
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                "Fusce malesuada lacus nec sapien hendrerit mollis. Etiam " +
                "euismod consequat magna sed ornare. Donec dapibus aliquet " +
                "turpis eget gravida. Morbi porttitor orci pharetra magna " +
                "ultrices, vel facilisis mauris ullamcorper. Curabitur a " +
                "fringilla arcu. Mauris vulputate sodales blandit.\n" + 
                "Nam pellentesque volutpat est vitae ultrices. Nam at augue " +
                "quis massa porttitor suscipit et ac neque. \n" + 
                "Cras dolor risus, lobortis nec nisl nec, suscipit iaculis " +
                "tellus. Nulla non bibendum elit, ut gravida lacus. " + 
                "est modi necessitatibus. \n" + 
                "Hic rerum voluptas voluptatem. \n" + 
                "Ut expedita unde eum molestias voluptatem aut" + 
                "dignissimos dolor. \n")

        cursor = QTextCursor(self.text_edit.document())
        cursor.select(QTextCursor.Document)
        fmt = QTextBlockFormat()
        fmt.setTextIndent(40)
        cursor.mergeBlockFormat(fmt)

app = QApplication(sys.argv)

widget = Widget()
widget.show()

app.exec()

I got that (and obviously since I'm adding a indent at every new paragraph): What I have

But what I'm aiming for is that:

What I'm expecting

I saw some people talking about QTextLayout for that, but I read and read again the doc and couldn't understand how I could make it work.


Solution

  • You can use setLeftMargin() and then use setTextIndent() with the same negative value.

    fmt.setLeftMargin(40)
    fmt.setTextIndent(-40)