2010-08-23 127 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

相關問題