限制qgraphicsitem的可移动区域

qua*_*dro 5 python pyqt pyqt4 qgraphicsview qgraphicsitem

有没有一种方法可以限制放置QGraphicsItem类似QRect物体时可以移动的区域setFlag(ItemIsMovable)

我是pyqt的新手,它试图找到一种方法来使用鼠标移动项目,并将其限制为仅垂直/水平方向。

Rob*_*ert 5

如果要保留有限的区域,可以重新实现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
Run Code Online (Sandbox Code Playgroud)

实现:需要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);
}
Run Code Online (Sandbox Code Playgroud)

然后我们定义场景的矩形,在这种情况下为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);

}
Run Code Online (Sandbox Code Playgroud)

这是为了将图形保持在一个区域内,祝您好运


Sim*_*bbs 1

您可能需要重新实现 的QGraphicsItem函数itemChange()

伪代码:

if (object position does not meet criteria):
    (move the item so its position meets criteria)
Run Code Online (Sandbox Code Playgroud)

重新定位该项目将导致itemChange再次被调用,但这没关系,因为该项目将被正确定位并且不会再次移动,因此您不会陷入无限循环。