Search code examples
pythonpysidepyside2pyside6pyqt6

How to make every paragraph in plaintextedit have indent in Pyside6?


I want every paragraph in plainTextEdit.text has text-indent.
I tried to use setTextIndent(). But it didn't work.
This is my code

from ui2 import Ui_Form
from PySide6.QtWidgets import QApplication,QWidget
from PySide6 import QtCore,QtGui
from PySide6.QtGui import QTextCursor


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

        doc=self.ui.plainTextEdit.document()
        a=doc.firstBlock().blockFormat()
        a.setTextIndent(100)
        cursor = QTextCursor(doc)
        cursor.setBlockFormat(a)
        cursor.insertText("This is the first paragraph\nThis is the second paragraph")
        print(self.ui.plainTextEdit.document().toPlainText())


app = QApplication([])
mainw = MainWindow()
mainw.show()
app.exec()

This is my print:

This is the first paragraph
This is the second paragraph

which don't have textindent.


Solution

  • You have to use QTextEdit:

    from PySide6.QtWidgets import QApplication, QTextEdit
    from PySide6.QtGui import QTextCursor
    
    app = QApplication([])
    
    te = QTextEdit()
    te.resize(640, 480)
    te.show()
    
    cursor = QTextCursor(te.document())
    block_format = cursor.blockFormat()
    block_format.setTextIndent(100)
    cursor.setBlockFormat(block_format)
    cursor.insertText("This is the first paragraph\nThis is the second paragraph")
    
    app.exec()
    

    enter image description here