跳过qgraphics场景中qgraphics项的mouseEvents

skipping the mouseEvents of the qgraphicsitem in a qgraphics scene

本文关键字:qgraphics 项的 mouseEvents 跳过      更新时间:2023-10-16

我知道如何将事件从qgraphics场景传递到qgraphics项,但问题是该项正在执行场景的鼠标事件。

例如,在下面的代码中,当按下项目时,输出为"自定义场景已按下"

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

请参阅QGraphicsSceneMouseEvent::pos:的文档

返回鼠标光标在项目坐标中的位置。

这意味着,如果鼠标距离物品的左上边框10个像素,无论物品在场景中的哪个位置,您都会得到(10,10)作为坐标。

您需要的是QGraphicsSceneMouseEvent::scenePos:

返回鼠标光标在场景坐标中的位置。

将您的if-声明更改为:

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