Limit qgraphicsitem moveable area

Is there a way to limit the area where a QGraphicsItem, like a QRect, can be moved when setFlag (ItemIsMovable) is set?

I am new to pyqt and trying to find a way to move an element with the mouse and limit it only vertically / horizontally.

Thanks!

+4
source share
3 answers

If you want to keep a limited scope, you can override ItemChanged ()

Declare:

#ifndef GRAPHIC_H #define GRAPHIC_H #include <QGraphicsRectItem> class Graphic : public QGraphicsRectItem { public: Graphic(const QRectF & rect, QGraphicsItem * parent = 0); protected: virtual QVariant itemChange ( GraphicsItemChange change, const QVariant & value ); }; #endif // GRAPHIC_H 

implementation : The ItemSendsGeometryChanges flag is needed to record a change in position of a QGraphicsItem

 #include "graphic.h" #include <QGraphicsScene> Graphic::Graphic(const QRectF & rect, QGraphicsItem * parent ) :QGraphicsRectItem(rect,parent) { setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemSendsGeometryChanges); } QVariant Graphic::itemChange ( GraphicsItemChange change, const QVariant & value ) { if (change == ItemPositionChange && scene()) { // value is the new position. QPointF newPos = value.toPointF(); QRectF rect = scene()->sceneRect(); if (!rect.contains(newPos)) { // Keep the item inside the scene rect. newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left()))); newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top()))); return newPos; } } return QGraphicsItem::itemChange(change, value); } 

Then we define the rectangle of the scene, in this case there will be 300x300

 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QGraphicsView * view = new QGraphicsView(this); QGraphicsScene * scene = new QGraphicsScene(view); scene->setSceneRect(0,0,300,300); view->setScene(scene); setCentralWidget(view); resize(400,400); Graphic * graphic = new Graphic(QRectF(0,0,100,100)); scene->addItem(graphic); graphic->setPos(150,150); } 

This means that the graph is inside the area, good luck

+4
source

reimplement mouseMoveEvent (self, event) in a QGraphicScene for example:

 def mousePressEvent(self, event ): self.lastPoint = event.pos() def mouseMoveEvent(self, point): if RestrictedHorizontaly: # boolean to trigger weather to restrict it horizontally x = point.x() y = self.lastPoint.y() self.itemSelected.setPos(QtCore.QPointF(x,y))<br> # which is the QgraphicItem that you have or selected before 

hope this helps

+3
source

You probably need to override the QGraphicsItem itemChange () function. Pseudocode:

 if (object position does not meet criteria): (move the item so its position meets criteria) 

Returning the item will cause itemChange to be called again, but this is normal because the item will be correctly entered and will not be moved again, so you won’t get stuck in an infinite loop.

+2
source

All Articles