How can I resize a QGraphicsTextItem including its text/contents in PyQt5?

270 views Asked by At

I made a QGraphicsTextItem and set plain text as its content. After that, I set the QGraphicsTextItem inside the QGraphicsWidget.

My question is, Is it possible to resize the QGraphicsTextItem including its text/contents like in this picture:

This is the video of the resizing that I'm asking for.

Video of Resizing

If this is possible, how can I apply it to the QGraphicsTextItem?

The first picture is the image of the QGraphicsTextItem but I have no idea how to implement the resizing in the video.

Things I've tried:

  • I tried using the setTextWidth() and setting it to 0.5 but it's not working.
  • I also tried using adjustSize() to the QGraphicsTextItem but it's also not working.

Code to reproduce the issue:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.view = QGraphicsView()

        scene = QGraphicsScene()

        #before resizing
        item = QGraphicsTextItem("Line 1 Line 2 Line 3")
        item.setFlags(QGraphicsWidget.ItemIsSelectable)
        item.setPos(self.view.mapToScene(2, 2))
        scene.addItem(item)

        #after resizing
        item_1 = QGraphicsTextItem("Line 1\nLine 2\nLine 3")
        item_1.setFlags(QGraphicsWidget.ItemIsSelectable)
        item_1.setPos(self.view.mapToScene(2, 30))
        scene.addItem(item_1)

        self.view.setScene(scene)

        self.setCentralWidget(self.view)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    app.exec_()
0

There are 0 answers