3

ドラッグできるQGraphicsView大きなものがあります。QGraphicsSceneには、ランダムな形状を持つことができるを表示するQGraphicsSceneサブクラス化されたQGraphicsItem( ) があります。(将来実装される追加機能のため、直接使用しません)TestItemQGraphicsPixmapItemQGraphicsPixmapItem

このアイテムを動かせるようにしたいのですが、ユーザーがアイテムの形状内で押した場合のみです。シェイプの外側にあるが の内側にある場合はboundingRectangle、その背後にあるシーンをドラッグします。これboundingRectangleは、 がシェイプよりもはるかに大きく、ユーザーには見えないためです。そのため、シーンを の近くにドラッグしようとしてもうまくいきませんPixmap

これは私のサブクラス化されたアイテムです:

TestItem::TestItem(QPointF position, QPixmap testImage, double width, 
                    double length, QGraphicsItem * parent):
    QGraphicsItem(parent),
    m_boundingRect(QRectF(0,0,5, 5)),
    m_dragValid(false),
    m_path(QPainterPath()),
    mp_image(new QGraphicsPixmapItem(this))
{
    setBoundingRect(QRectF(0,0,width,length));
    setPos(position - boundingRect().center());
    setFlag(QGraphicsItem::ItemIsMovable);
    mp_image->setPixmap(testImage.scaled(width, length));
    m_path = mp_image->shape();
}

QPainterPath TestItem::shape()
{
    return m_path;
} 

QRectF TestItem::boundingRect() const
{
    return m_boundingRect;
}

void TestItem::setBoundingRect(QRectF newRect)
{
    prepareGeometryChange();
    m_boundingRect = newRect;
}

このようにマウスイベントをオーバーライドしようとしましたが、形状の外側ではなく境界長方形の内側では機能がまったくありません

void TestItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(shape().contains(event->pos()))
    { 
        QGraphicsItem::mousePressEvent(event);
        m_dragValid = true;
    }
}

void TestItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if(m_dragValid)
        QGraphicsItem::mouseMoveEvent(event);
} 

void TestItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if(m_dragValid)
        QGraphicsItem::mouseReleaseEvent(event);

    m_dragValid = false;
}

もちろんこれは理にかなっていますが、マウスイベントをグラフィックアイテムに送信するのはシーン自体であるため、シーンのドラッグを実装する方法はわかりません。

(私のQGraphicsViewは に設定されていますDragMode QGraphicsView::ScrollHandDrag)

誰にもアイデアがありますか?

4

2 に答える 2

4

私はそれを考え出した。event->ignore();マウスイベントに a を追加するだけで済みました。

void TestItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
   if(shape().contains(event->pos()))
    {  
        QGraphicsItem::mousePressEvent(event);
        m_dragValid = true;
    }
    else
        event->ignore();
}

void TestItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if(m_dragValid)
         QGraphicsItem::mouseMoveEvent(event);
    else
        event->ignore();
} 

void TestItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if(m_dragValid)
        QGraphicsItem::mouseReleaseEvent(event);
    else
        event->ignore();

    m_dragValid = false;
}
于 2015-01-21T08:42:00.590 に答える