Home > Enterprise >  How to indent paragraph in QtextEdit
How to indent paragraph in QtextEdit

Time:08-14

All works, but "def insertFromMimeData" doesn't works in my code. What is problem?)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))

def insertFromMimeData(self, md) doesn't works

import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QTextEdit, QApplication
from PyQt5.QtGui import QTextDocument, QTextCursor, QTextBlockFormat
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(608, 349)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(143, 50, 311, 211))
        self.textEdit.setObjectName("textEdit")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 608, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        cursor = QTextCursor(self.textEdit.document())
        cursor.select(QTextCursor.Document)
        fmt = QTextBlockFormat()
        fmt.setTextIndent(60)
        cursor.mergeBlockFormat(fmt)
    def insertFromMimeData(self, md):
        cursor = self.textEdit.textCursor()
        fmt = QTextBlockFormat()
        fmt.setTextIndent(cursor.blockFormat().textIndent())
        сursor.mergeBlockFormat(fmt)
        cursor.insertText(md.text())
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        MainWindow = QtWidgets.QMainWindow()
        ui = Ui_MainWindow()
        ui.setupUi(MainWindow)
        MainWindow.show()
        sys.exit(app.exec_())

CodePudding user response:

Use QTextEdit with indented text

UPD As @ВалерияГригорьева rightfully pointed out, the indent is discarded when pasting plain text (although I would expect it should be taken from the current block by the default implementation). Therefore we need to override QTextEdit.insertFromMimeData and apply indentation on insert:

cursor = self.textCursor()
fmt = QTextBlockFormat()
fmt.setTextIndent(cursor.blockFormat().textIndent())
cursor.mergeBlockFormat(fmt)
cursor.insertText(md.text())

For pasting the rich text, on the other hand, we don't want to suppress indents because they are a part of the rich text formatting and thus we can rely on the default implementation of QTextEdit.insertFromMimeData.

Complete code sample (for PyQt5):

import sys
from PyQt5.QtWidgets import QTextEdit, QApplication
from PyQt5.QtGui import QTextDocument, QTextCursor, QTextBlockFormat


class TextEditor(QTextEdit):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # format text edit
        self.setPlainText(
                "Impedit voluptatem sequi quae quo quos. \n"   
                "Asperiores non repellat culpa nihil. \n"   
                "Voluptatum ut numquam dolorem molestiae voluptatem "   
                "est modi necessitatibus. \n"   
                "Hic rerum voluptas voluptatem. \n"   
                "Ut expedita unde eum molestias voluptatem aut"   
                "dignissimos dolor. \n"   
                "Non illo dolore ut doloremque ut.")
        cursor = QTextCursor(self.document())
        cursor.select(QTextCursor.Document)
        fmt = QTextBlockFormat()
        fmt.setTextIndent(60)
        cursor.mergeBlockFormat(fmt)
        # setup UI
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Text indent')
        self.show()

    def insertFromMimeData(self, md):
        # leave processing of the rich text as it is
        if md.hasFormat("application/x-qrichtext") or md.hasHtml():
            super().insertFromMimeData(md)
        else:
            # force indentation from the current block 
            # (shouldn't Qt do this by default, huh?)
            cursor = self.textCursor()
            fmt = QTextBlockFormat()
            fmt.setTextIndent(cursor.blockFormat().textIndent())
            cursor.mergeBlockFormat(fmt)
            cursor.insertText(md.text())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = TextEditor()
    sys.exit(app.exec())
  • Related