6

QGraphicsItemが設定されている場合、いいねQRectを移動できる領域を制限する方法はありsetFlag(ItemIsMovable)ますか?

私はpyqtが初めてで、マウスでアイテムを移動する方法を見つけようとしており、垂直/水平のみに制限しています。

4

3 に答える 3

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

実装:QGraphicsItemの位置の変更をキャプチャするには、ItemSendsGeometryChangesフラグが必要です

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

}

これは、グラフを領域内に保持するためです。幸運を祈ります

于 2011-11-05T05:18:39.943 に答える
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

それが役に立てば幸い

于 2010-09-22T12:46:11.810 に答える
1

QGraphicsItemおそらく、のitemChange()関数を再実装する必要があります。

擬似コード:

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

アイテムの位置を変更itemChangeすると再度呼び出されますが、アイテムは正しく配置され、再度移動することはないので問題ありません。無限ループに陥ることはありません。

于 2010-08-24T10:28:06.927 に答える