如何在QGraphicsItem中插入指针,以便在他们获得选定指针时访问



我想用鼠标点击在场景中选择矩形/多段线,并且应该能够打印它的名称和其他属性。它的名称和其他属性在图形节点中。但我不想再和图形交互了。

因此,当我通过图形坐标绘制矩形/多段线时,我应该能够将图形节点的一些指针存储在矩形/多线上,这样当我单击矩形/多条线时,通过该指针我可以访问它的名称和其他属性。

问题是"这可能吗?"?

在以上所有参数中,我只想存储_Ptr(它基本上是一个指针,但存储为long,而使用它将是类型转换(

rect = new myRect();
while(true)
{    

for(auto iter = verts.begin();iter != verts.end();++iter)
{
// getting co-ordinates of rectangle     
QGraphicsRectItem* rectItem = rect->createRect(co-ordinates of rectangle);
rect->_Ptr =  iter->_Ptr;  // trying to store _crossRefPtr  
}
}    

myRect.h

class myRect : public QGraphicsRectItem
{
........
QGraphicsRectItem* createRect(QRectF& rect);       

}        

当我用鼠标点击场景中的矩形时,我会这样做:

if(_scene->selectedItems().count() != 0)
{
foreach(QGraphicsItem* currentItem, _scene->selectedItems())
{
QGraphicsRectItem* rItem = qgraphicsitem_cast<QGraphicsRectItem*>(currentItem);
if(rItem)
{
myRect* r = reinterpret_cast<myRect*>(rItem);
if(r)
{
Instance (rectangle)
Instance* i = reinterpret_cast<Instance*>(r->_boostRefPtr); 
qDebug()<< i->Name();
}
}     

但无论如何都是错误的。获取运行时错误(显示详细堆栈跟踪(
所以问题是:

如何将指针存储在QGraphicsItem上,这样,一旦它们被选中,该指针将被访问?

使用Qt的动态属性,检查QObject::setProperty。它应该起作用。

但是AFAIC,我会使用一个双QMap来直接关联<graph_node, QGraphicsItem>AND<QGraphicsItem, graph_node>-这样你就可以快速搜索这两个关联,并且都具有O(log2(n((复杂性。您可以将其存储为图形的静态部分(更好(或独立部分(不是最好的主意(。显然,如果你的图已经在O(log2(n((中,你不需要这个映射,你只需要<QGraphicsItem, graph_node>映射。

最新更新