質問

I have 2 custom qgraphicsitems on a qgraphicsScene, rendered by a qgraphicsview. Now I want to be able to drag and drop one of the 2 items to the other kind. But which events should I reimplement for this? The documentation is a bit confusing on this.

also I want the qgraphicsitem to jump back to its original position if the user drags it to another area than the qgraphicsitem it should be dropped on.

役に立ちましたか?

解決

As far as i know this is not implemented in the QGraphicsScene itself. You must derive your own class from QGraphicsView or QGraphicsScene and then overload:

class MyGraphicsView : public QGraphicsView
{
    Q_OBJECT;
protected:
    virtual void mousePressEvent(QMouseEvent* event);
    virtual void mouseMoveEvent(QMouseEvent* event);
    virtual void mouseReleaseEvent(QMouseEvent* event);
    ...
private:
    QGraphicsItem *currentDraggedItem;
};

QGraphicsView gives works with view/window coordinates while QGraphicsScene works with Scene coordinates.

Add code like:

void MyGraphicsView::mousePressEvent(QMouseEvent* event)
{
    currentDraggedItem = itemAt(event->pos());

    QGraphicsView::mousePressEvent(event);
}
void MyGraphicsView::mouseReleaseEvent(QMouseEvent* event)
{
    QGraphicsItem *foundItem = itemAt(event->pos());
    if(foundItem && currentDraggedItem && 
       foundItem != currentDraggedItem)
    {
       // Handle DragDrop Here
    }

    QGraphicsView::mouseReleaseEvent(event);
}

This does the job for one QGaphicsScene. If you have two of them - the both have to know each other and you must translate coordinates from the one QGraphicsView to the other QGraphicsView. using mapTo...().

他のヒント

The key to this is checking the QGraphicsItems rect and seeing if they intersect.

So, when the mouse down is pressed on an item, store its current position. You can now move it and wait for the mouse release. On the release of the mouse button, check if the bounding rects of the items intersect with QRect::contains(const QRectF). If they do, then you've dropped one onto the other. If not, then animate the graphics item back to the previously stored position.

Just make sure that when you're checking the bounding rects for intersection that you're doing this with both of them in scene space coordinates. Either convert them, or use QGraphicsItem::sceneBoundingRect().

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top