Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

QTextEdit alignment fails on pasting text

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_())

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading