PDA

View Full Version : Define the bounds of a Item in a QGraphicsView



Pedro Monteiro
19th December 2015, 08:29
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 with the mouse I can pass the image boundaries and I wanted to limit the rectangle to the image boundary, how could I do that?
The answer can be in C++.
My image with rectangle (http://imgur.com/E1zYfwJ)
Thanks.



# -*- 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()

anda_skoa
19th December 2015, 10:21
You override the itemChange() method, handle the position change and return an acceptable value if given value is not.

Cheers,
_