Important: Please read the Qt Code of Conduct -

How to resize a item QGraphicsView?

  • Hello, I made an application using the Qt Designer and PyQt4, I'm using QGraphicsView to display an image with a rectangle on it, I can move the rectangle over the image, but when I move it I can pass the image boundaries and I wanted to limit the rectangle to the image boundary, how could I do that? And another question, how could I change the size of the rectangle using the mouse?

    Down a code I'm using for testing, it gets QGraphicsView I did in Designer:

    # -*- coding: utf-8 -*-
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    import sys
    from screen import *
    class Main(QWidget, Ui_Form):
    	def __init__(self, parent=None):
    		super(Main, self).__init__(parent)
    		self.scene = QGraphicsScene()
    		pen = QPen(Qt.darkMagenta)
    		rectangle = self.scence.addRect(5,5,300,150, pen)
    	def showEvent(self, event):
    		self.cena.fitInView(self.scene.sceneRect(), Qt.IgnoreAspectRatio)
    app = QApplication(sys.argv)
    window = Main()

    The answer can be in C++ or Python.

  • Moderators

    i will give you an (rough) overview what has to be done:


    1. subclass QGraphicsRectItem (add the rect-item as a child of the pixmap item)
    2. on itself call setFlags(QGraphicsItem::ItemSendsGeometryChanges)
    3. override itemChange() and listen to QGraphicsItem::ItemPositionChange and check the value if it is in the parent-item's rect/shape. If not return the adapted value


    1. override the paint event handler of the created custom rect item and paint 4 small rects in each corner of the rect
    2. overrride mousePressEvent() handler and check if the mouse was clicked on a handle, if so save the handle direction in a local variable
    3. overrride mouseMoveEvent() handler and check the variable for the direction, calculate the diff-distance between the last position and the current move-position. Add the diff to the current rect of the item. Also make sure the (like you also have done it for MOVING) that the rect stays inside the parent-item's rect
    4. overrride hoverMoveEvent() handler in case you want to change the cursor when the cursor is over one of the handles

  • @raven-worx I already solved about moving, but the resizing looks hard to do, is there some example, even in C++?

Log in to reply