Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
How to resize a item QGraphicsView?
Pedro_Monteiro last edited by Pedro_Monteiro
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.setupUi(self) self.scene = QGraphicsScene() self.cena.setScene(self.scene) self.scene.addPixmap(QPixmap("01.png")) pen = QPen(Qt.darkMagenta) pen.setWidth(4) rectangle = self.scence.addRect(5,5,300,150, pen) rectangle.setFlag(QGraphicsItem.ItemIsMovable) def showEvent(self, event): self.cena.fitInView(self.scene.sceneRect(), Qt.IgnoreAspectRatio) app = QApplication(sys.argv) window = Main() window.show() sys.exit(app.exec_())
The answer can be in C++ or Python.
i will give you an (rough) overview what has to be done:
- subclass QGraphicsRectItem (add the rect-item as a child of the pixmap item)
- on itself call setFlags(QGraphicsItem::ItemSendsGeometryChanges)
- 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
- override the paint event handler of the created custom rect item and paint 4 small rects in each corner of the rect
- overrride mousePressEvent() handler and check if the mouse was clicked on a handle, if so save the handle direction in a local variable
- 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
- overrride hoverMoveEvent() handler in case you want to change the cursor when the cursor is over one of the handles
Pedro_Monteiro last edited by
@raven-worx I already solved about moving, but the resizing looks hard to do, is there some example, even in C++?