简体   繁体   中英

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();
}

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.";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM