Issue
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
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
Answered By - musicamante
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.