限制QGraphicsItem的移动区域

7 投票
3 回答
4194 浏览
提问于 2025-04-16 03:10

有没有办法限制一个像 QRect 这样的 QGraphicsItem 在设置了 setFlag(ItemIsMovable) 后的移动区域?

我刚接触pyqt,想找个方法让一个物体可以用鼠标移动,但只想限制它在垂直或水平方向上移动。

3 个回答

1

你可能需要重新实现一下 QGraphicsItemitemChange() 函数。

伪代码:

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

当你重新调整这个项目的位置时,itemChange 函数会再次被调用,但这没关系,因为这个项目会被正确放置,不会再移动,所以你不会陷入一个无尽的循环中。

4

在QGraphicScene中重新实现mouseMoveEvent(self,event)方法,像下面这样:

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

希望这对你有帮助

7

如果你想保持一个有限的区域,可以重新实现 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);

}

这样做是为了让图形保持在一个区域内,祝你好运!

撰写回答