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

QGraphicsScene的itemAt()无法检测QGraphicsEllipseItem问题

问题解决:QGraphicsScene::itemAt()返回空但图形可见

核心原因推测

你的测试代码存在异步信号槽延迟问题:通过QTest模拟按键触发绘图逻辑后,信号槽的执行是异步的(Qt默认跨对象的信号槽为QueuedConnection),此时直接调用itemAt()检查,item还未被添加到场景中,导致返回空。

解决方案

在测试代码的按键操作后,添加事件循环处理,等待所有pending事件执行完毕:

void TestGUI::testPoint() {

  QVERIFY(repl && replEdit);
  QVERIFY(canvas && scene);

  // send a string to the repl widget
  QTest::keyClicks(replEdit, "(draw (point 0 0))");
  QTest::keyClick(replEdit, Qt::Key_Return, Qt::NoModifier);

  // 等待事件循环处理完信号槽逻辑
  QApplication::processEvents(QEventLoop::AllEvents, 1000);

  // check canvas
  QVERIFY2(scene->itemAt(QPointF(0, 0), QTransform()) != 0,
           "Expected a point in the scene. Not found.");
}

额外排查点(如果上述方案无效)

  • 验证图形是否真的包含目标点:在addGraphic中添加打印,确认item的shape包含(0,0):
    qDebug() << "Item contains (0,0):" << item->contains(QPointF(0,0));
    
    如果返回false,检查exp.head.value.point_value.x/y的实际值是否为0,或者pointradius是否为有效数值。
  • 检查场景坐标系与视图变换:如果你的QGraphicsView有缩放、平移等变换,调用itemAt时需要传入视图的变换矩阵,而不是单位矩阵:
    scene->itemAt(canvas->view->mapToScene(QPoint(0,0)), canvas->view->transform());
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:32:19