c++ - 在 qgraphicsscene 中跳过 qgraphicsitem 的鼠标事件

标签 c++ qt

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

例如在下面的代码中,当按下项目时输出是“自定义场景被按下”

 #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 的文档:

Returns the mouse cursor position in item coordinates.

这意味着如果鼠标距离项目的顶部和左侧边框 10 像素,无论项目在场景中的哪个位置,您都将获得 (10,10) 作为坐标。

你需要的是QGraphicsSceneMouseEvent::scenePos :

Returns the mouse cursor position in scene coordinates.

将您的 if 语句更改为:

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

关于c++ - 在 qgraphicsscene 中跳过 qgraphicsitem 的鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17270121/

相关文章:

c++ - static lock_guard 和 static mutex 也一样吗?

python - 无法使用 PyQt4 中的 QProcess 放弃新进程的权限

Qt显示带有文本输入的消息框

c++ - 在非常大的算术系列中添加数字的最快方法?

c++ - 使用 std::binomial_distribution 计算概率

c++ - 在命令行编译c++ boost测试程序

c++ - 构造对象的歧义

qt - 在 Qt Creator 中运行 Debug模式

android - 自定义 QML 模块部署到 Android : QML dependencies missing

c++ - 在 Qt 代码上使用 Fortify SCA(未过时 "HP Fortify")