@SGaist hi, I managed to fix it but my solution looks very over-engineered to me... I've also tried your suggestion but by itself it does not really work as intended.
def _center_text(self):
width = max(0, self.viewport().width() - 20)
doc = self._text.document()
doc.setTextWidth(width)
self.centerOn(self._text)
This does not really work because the problem is that the text itself is not centered. So, the text item is occupying width of whole viewport but text is on the left anyway, though wrap works correctly.
def _center_text(self):
width = max(0, self.viewport().width() - 20)
doc = self._text.document()
doc.setTextWidth(-1)
natural_width = doc.idealWidth()
text_width = min(natural_width, width)
doc.setTextWidth(text_width)
self.centerOn(self._text)
This works almost as intended, but the wrapped text is again on the left. So the text is in the center when it has only one line, the effect is broken when wrap is introduced.
def _center_text(self):
width = max(0, self.viewport().width() - 20)
doc = self._text.document()
doc.setTextWidth(-1)
natural_width = doc.idealWidth()
text_width = min(natural_width, width)
doc.setTextWidth(text_width)
self.centerOn(self._text)
cursor = QTextCursor(doc)
block_format = QTextBlockFormat()
block_format.setAlignment(Qt.AlignCenter)
cursor.select(QTextCursor.Document)
cursor.mergeBlockFormat(block_format)
These crazy additional lines which I barely found make the centered text even for the wrapped version.
However, I still had some weird effect in my real app when first position of the text was wrong, but after any resize it would normalize. This is most likely because the widget there is not visible by default so some sizes are not properly calculated. I am not sure how to solve this with centerOn. Tried several things but problem persisted or the location broke completely. So I returned to setPos and even had to add setSceneRect on top of that. With this solution I get correct behavior at all time: different sizes, hiding/showing widget, switching between tabs... Amount of code required just for centering the text is crazy though, so if someone has improvement ideas, they are welcome here.
def _center_text(self):
width = max(0, self.viewport().width() - 20)
height = max(0, self.viewport().height() - 20)
self._scene.setSceneRect(QRectF(0, 0, width, height))
doc = self._text.document()
doc.setTextWidth(-1)
natural_width = doc.idealWidth()
text_width = min(natural_width, width)
doc.setTextWidth(text_width)
cursor = QTextCursor(doc)
block_format = QTextBlockFormat()
block_format.setAlignment(Qt.AlignCenter)
cursor.select(QTextCursor.Document)
cursor.mergeBlockFormat(block_format)
text_rect = self._text.boundingRect()
scene_rect = self._scene.sceneRect()
center_x = scene_rect.center().x() - text_rect.width() / 2
center_y = scene_rect.center().y() - text_rect.height() / 2
self._text.setPos(center_x, center_y)