Radwa
Radwa

Reputation: 117

skipping the mouseEvents of the qgraphicsitem in a qgraphics scene

I know how to pass events from qgraphics scene to q graphics item ,but the problem is for the item,the mouse events for the scene is being executed.

for example in the code below when pressing on the item the output is "custom scene is pressed"

 #include <QtGui>
class CustomScene : public QGraphicsScene
{
protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event)
    {
        if(itemAt(event->pos()))
            QGraphicsScene::mousePressEvent((event));
        else
        qDebug() << "Custom scene clicked.";
    }
};
class CustomItem : public QGraphicsRectItem
{
protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event)
    {
        qDebug() << "Custom item clicked.";
    }
};
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    CustomItem item;
    item.setRect(20, 20, 60, 60);
    CustomScene scene;
    //scene().set
    scene.addItem(&item);
    QGraphicsView view;
    view.setScene(&scene);
    view.show();
    return a.exec();
}

Upvotes: 2

Views: 151

Answers (1)

Tim Meyer
Tim Meyer

Reputation: 12600

See the documentation of QGraphicsSceneMouseEvent::pos:

Returns the mouse cursor position in item coordinates.

This means if the mouse is 10 pixels away from the top and left border of your item, you will get (10,10) as coordinates no matter where on the scene the item is.

What you need is QGraphicsSceneMouseEvent::scenePos:

Returns the mouse cursor position in scene coordinates.

Change your if-statement to:

 if(itemAt(event->scenePos()))
    QGraphicsScene::mousePressEvent((event));
 else
    qDebug() << "Custom scene clicked.";

Upvotes: 1

Related Questions