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
相关产品推荐
相关产品推荐

