You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让QGraphicsItemGroup子元素不可选中 使itemAt返回对应父组

解决方案

你之前调用setFiltersChildEvents(True)不生效是因为该方法仅控制事件投递逻辑,不会影响itemAt()的项查找规则,有两种可行方案解决你的问题:

方案1:设置子项不可选中(实现更简单)

直接禁用所有组内子项的选中和焦点能力,让itemAt()仅返回可选中的父组即可,操作步骤如下:

  • 给所有添加到QGraphicsItemGroup的子项移除可选、可焦标志:
    // 单个子项设置示例
    childItem->setFlags(childItem->flags() & ~Qt::ItemIsSelectable & ~Qt::ItemIsFocusable);
    
  • 确保QGraphicsItemGroup本身开启可选标志:
    groupItem->setFlags(groupItem->flags() | Qt::ItemIsSelectable);
    

方案2:查询后递归查找顶层父组(不修改子项属性)

如果业务需要保留子项的可选中属性,可以在拿到itemAt()的返回结果后,通过递归查询找到子项所属的顶层组,工具函数示例:

QGraphicsItem* getTopItemGroup(QGraphicsItem* currentItem) {
    if (!currentItem) return nullptr;
    // 循环向上查找父项,直到没有QGraphicsItemGroup类型的父项为止
    while (currentItem->parentItem()) {
        QGraphicsItemGroup* parentGroup = dynamic_cast<QGraphicsItemGroup*>(currentItem->parentItem());
        if (!parentGroup) break;
        currentItem = parentGroup;
    }
    return currentItem;
}

使用时直接对itemAt()的返回值做二次处理即可:

QGraphicsItem* hitItem = scene->itemAt(mousePos, viewTransform);
QGraphicsItem* targetGroup = getTopItemGroup(hitItem);

内容的提问来源于stack exchange,提问作者Tonio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:00:02