Ограничить подвижную область qgraphicsitem
Есть ли способ ограничить область, где QGraphicsItem
лайк QRect
может быть перемещен, когда setFlag(ItemIsMovable)
установлен?
Я новичок в pyqt и пытаюсь найти способ перемещения элемента с помощью мыши, и ограничить его только вертикально / горизонтально.
3 ответа
Если вы хотите сохранить ограниченную область, вы можете переопределить ItemChanged()
Объявляет:
#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
реализация: флаг ItemSendsGeometryChanges необходим для захвата изменения положения 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);
}
Затем мы определяем прямоугольник сцены, в этом случае будет 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);
}
Это чтобы держать график в пределах области, удачи
Реализуйте mouseMoveEvent(self,event) в QGraphicScene следующим образом:
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
Надеюсь, поможет
Вы, вероятно, должны были бы повторно реализовать QGraphicsItem
"s itemChange()
функция.
псевдокод:
if (object position does not meet criteria):
(move the item so its position meets criteria)
Изменение позиции приведет к itemChange
вызывать снова, но это нормально, потому что элемент будет расположен правильно и больше не будет перемещаться, так что вы не застрянете в бесконечном цикле.