Home > Software design >  QTextEdit alignment fails on pasting text
QTextEdit alignment fails on pasting text

Time:06-10

i used QTextEdit and used alignment to make it center , it work fine as long as i'm writing but if i copy and paste text to it, it breaks the alignment and start to write from left to right, how to make it always align text to center!

import sys
from PySide2 import QtWidgets, QtCore 

class App(QtWidgets.QWidget):

    def __init__(self):
        super().__init__()
        layout = QtWidgets.QVBoxLayout(self)
        text = QtWidgets.QTextEdit('CENTERED TEXT BUT IF YOU PASTE STH IT ALIGNS LEFT')
        text.setAlignment(QtCore.Qt.AlignCenter)
        text.setFixedHeight(100)
        layout.addWidget(text)
        self.setLayout(layout)
        self.show()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

CodePudding user response:

As the documentation about setAlignment() explains, it "Sets the alignment of the current paragraph". While creating a new paragraph usually keeps the current text format, pasting text from outside sources that support rich text (i.e.: a web page) will override it.

You have to alter the block format for the whole document using the QTextCursor interface.

class CenterTextEdit(QtWidgets.QTextEdit):
    updating = False
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.textChanged.connect(self.updateAlignment)
        self.updateAlignment()

    def updateAlignment(self):
        if self.updating:
            # avoid recursion, since changing the format results
            # in emitting the textChanged signal
            return
        self.updating = True
        cur = self.textCursor()
        cur.setPosition(0)
        cur.movePosition(cur.End, cur.KeepAnchor)
        fmt = cur.blockFormat()
        fmt.setAlignment(QtCore.Qt.AlignCenter)
        cur.mergeBlockFormat(fmt)
        self.updating = False
  • Related