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

自定义TreeViewNode节点mousePressEvent未触发问题求助

问题分析与解决方案

1. 核心根源:boundingRect()未正确实现

QGraphicsItem的鼠标事件触发完全依赖**boundingRect()返回的碰撞区域**。如果这个函数未返回节点实际绘制的完整范围,点击操作会被判定为"未命中"节点,直接导致mousePressEvent不执行。

你仅在头文件中声明了boundingRect()但未提供实现,这是最可能的问题。需根据节点的绘制逻辑,返回包含所有绘制内容的矩形,示例实现:

QRectF TreeViewNode::boundingRect() const {
    // 根据你的实际绘制尺寸调整数值,留出少量边距避免点击失效
    return QRectF(-50, -25, 100, 50);
}

2. 修复构造函数中的错误return逻辑

构造函数中处理亲属节点时,一旦检测到节点已存在就直接return,会中断当前节点的后续初始化(比如创建母亲、配偶、子节点),甚至导致部分节点状态异常。需将return改为跳过当前分支:

原错误代码:

if (addedNodes.count(father) > 0) {return;}

修改为:

// 处理父亲节点
if (m_node->getFather() && !addedNodes.count(m_node->getFather())) {
    TreeViewNode* fatherNode = new TreeViewNode(m_node->getFather(), family, m_scene, this);
    fatherNode->setPos(-50, -100);
}

// 处理母亲节点
if (m_node->getMother() && !addedNodes.count(m_node->getMother())) {
    TreeViewNode* motherNode = new TreeViewNode(m_node->getMother(), family, m_scene, this);
    motherNode->setPos(50, -100);
}

3. 补全信号槽连接的覆盖范围

你当前仅连接了根节点treeView的clicked信号,但子节点的信号未绑定到updateSelectedPatient槽函数,点击子节点不会触发响应。可在TreeViewNode构造函数中统一处理连接(需传入MainWindow指针):

// TreeViewNode构造函数新增参数MainWindow* mainWin
TreeViewNode::TreeViewNode(node* node, Family_tree* family, QGraphicsScene* scene, MainWindow* mainWin, QGraphicsItem* parent) 
    : QGraphicsItem(parent), m_node(node), m_family(family), m_scene(scene) {
    // 原有初始化逻辑...
    connect(this, &TreeViewNode::clicked, mainWin, &MainWindow::updateSelectedPatient);
}

4. 辅助验证步骤

  • 在paint()函数中临时绘制boundingRect边框,直观检查碰撞区域是否匹配:
    void TreeViewNode::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
        // 原有绘制代码...
        // 临时绘制边框,测试完成后删除
        painter->drawRect(boundingRect());
    }
    
  • 确认QGraphicsView的setInteractive(true)已调用(默认开启,可手动验证),且视图未被其他控件遮挡。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:02:57