子类QGraphicsItem使我无法在QGraphicsScene/View上使用itemAt()
Subclassing QGraphicsItem prevents me from being able to use itemAt() on a QGraphicsScene/View
我已经将QGraphicsItem子类化为我自己的自定义类Hexagon。当我尝试使用QGraphicsView::itemAt
或QGraphicsScene::itemAt
之类的函数时,它不会返回任何Hexagon
对象,因为该函数会查找QGraphicsItems
如何告诉它查找Hexagon
对象?还是我需要更改Hexagon
类中的某些内容?甚至重新实施itemAt()
?
目前,我还在对QGraphicsView
,特别是mousePressedEvent
进行子类化,以获得有关单击的Hexagon
对象的一些信息
void LatticeView::mousePressEvent(QMouseEvent *event)
{
Hexagon *hexagon = itemAt(event->pos());
...
}
但当我尝试编译时,我会得到以下错误:
从"QGraphicsItem*"到"Hexagon*"的转换无效
我想要的是能够获得被点击的Hexagon
对象,这样我就可以访问我在Hexagon
类中定义的一些在QGraphicsItem
类中不隐含的变量。
要实现这一点,您需要先强制转换指针,然后再将其分配给另一种类型的指针变量。。
Hexagon *hexagon = (Hexagon*)itemAt(event->pos());
但是这里存在危险,因为itemAt()
可能返回NULL
或者该项目可能不是Hexagon
项目。
事实上,您应该像这样使用C++样式的转换:
Hexagon *hexagon = dynamic_cast<Hexagon*>(itemAt(event->pos()));
if (hexagon != NULL)
{
hexagon->hexagonMethod();
}
这需要通过编译器获得运行时类型信息。
还有一个名为type()的QGraphicsItem
函数,它将允许您使用qgraphicsitem_cast()
,但这需要一些额外的工作,包括定义enum
。
还有一件事需要注意。根据场景和项目使用鼠标事件的方式,您可能不会总是看到mousePressEvent()
的覆盖在您期望的时候被调用,因为如果鼠标事件被场景中的某个东西使用,它可能永远不会到达视图。
相关文章:
- 如何从未知视图中声明范围::v3::View 变量
- bsoncxx: document::view vs document::value
- 在并行算法中使用 ranges::view::iota
- 复制 Simd::View 的一部分
- Getter and Setter for a View
- 范围中的"range"和"view"有什么区别sv3 ts?
- C++中的numpy“.view”函数
- Eigen::map 真的有"view"语义吗
- 通过 itemAt() 或 collidingItems() 返回自定义 QGraphicsItem
- 防止 QGraphicsItem::itemAt() 在"Background Item"上
- Boost.Hana中是否有类似Boost.Fusion的View概念
- opencv/view studio:错误LNK2019:未解析的外部符号
- C++ 错误:请求成员'view'
- 如何在 GDB 中配置 STL-View
- View a .h class
- Qt 5.0.2 简单 qWeb View 上的内存泄漏
- 为什么我不能在SQLite中的VIEW上创建触发器
- 在Qt5中更改QGraphicsScene/View中的Pixmap位置
- 子类QGraphicsItem使我无法在QGraphicsScene/View上使用itemAt()
- Qt4:QGraphicsScene/View和自定义转换方法