3

我有QGraphicsView一个更大QGraphicsScene的可以拖动的。在QGraphicsScene我有一个显示 a的子类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();我的鼠标事件中添加一个。

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 回答
0

您只需要启用QGraphicsItem::ItemClipsToShape标志:

项目剪辑成自己的形状。该项目无法在其形状之外绘制或接收鼠标、平板电脑、拖放或悬停事件。默认情况下禁用。

于 2015-01-20T23:57:22.730 回答