2010-08-23 143 views
4

当setFlag(ItemIsMovable)被设置时,是否有办法限制像QRect这样的QGraphicsItem可以移动的区域?限制qgraphicsitem的可移动区域

我是pyqt的新手,并试图找到一种方法来移动一个项目与鼠标,并限制它只能垂直/水平。

谢谢!

回答

2

您可能需要重新实现QGraphicsItem的itemChange()函数。伪代码:

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

Repossitioning该项目将导致itemChange来再次调用,但没关系,因为该项目将被正确possitioned,不会再移动,所以你不能在一个无限循环被卡住。

3

重新实现在QGraphicScene 的mouseMoveEvent(自我,事件),如下所示:

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 

希望它有助于

4

如果你想保持一个有限的区域,你可以重新实现ItemChanged()

宣告:

需要 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); 
} 

然后我们定义场景的矩形的变化,在这种情况下将是300×300

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); 

} 
#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 

实施

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

+0

它工作得很好,希望Graphic项目可以在右下区域的场景外拖动一点点,因为您正在使用Graphic框的左上角坐标来验证对象是否位于场景矩形内。 – danger89 2016-03-15 11:59:27

+0

这可以解决它: http://stackoverflow.com/a/22559758/518879 – danger89 2016-03-15 12:32:30