qt QGraphicsScene additem

qt QGraphicsScene additem

本文关键字:additem QGraphicsScene qt      更新时间:2023-10-16

http://qt-project.org/doc/qt-4.8/qgraphicsscene.html#addItem

所述

如果项目已经在另一个场景中,它将首先从旧场景中删除,然后作为顶级。

我想把这个项目保留在旧的场景中。我该怎么做?

myscene1.addItem(item);
myscene2.addItem(item);// I don't want to remove item from myscene1

您可以复制项目:

myscene1.addItem(item);
myscene2.addItem(item->clone());

一个项目不能同时占据两个场景,就像你不能同时在两个地方一样。

唯一的方法是制作项目的副本并将其放置在第二个场景中。

您可以做的就是创建一个新的类。例如

class Position
{
   ...
   QPoinfF pos;
   ...
}

然后您可以将该类添加到项目中。

class Item : public QGraphicsItem
{
   ...
public:
   void setSharedPos(Position *pos)
   {
      sharedPosition = pos;
   }
   //implement the paint(...) function
   //its beeing called by the scene
   void paint(...)
   {
      //set the shared position here
      setPos(sharedPos);
      //paint the item
      ...
   }
protected:
   void QGraphicsItem::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event )
   {
      //get the position from the item that could have been moved
      //you could also check if the position actually changed
      sharedPosition->pos = pos();
   }
private
   Position *sharedPostion;
   ...
}

您不必创建两个项目,并为它们提供指向Position对象的相同指针。

Item *item1 = new Item;
Item *item2 = new Item;
Position *sharedPos = new Position;
item1->setSharedPos(sharedPos);
item2->setSharedPos(sharedPos);
myScene1->addItem(item1);
myScene2->addItem(item2);

他们至少不应该分享他们在幕后的立场。如果这样做有效,那么您必须更改Position类以满足您的需求,并且它应该是有效的。

如果在paint((函数中设置位置有效,我不太清楚。但这就是我尝试同步项目的方式。如果它不起作用,那么你将不得不寻找另一个地方来更新项目的设置。

或者你可以给这些项目一个指向彼此的指针,让它们直接更改位置/设置。

例如

class Item : public QGraphicsItem
{
...
   void QGraphicsItem::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event )
   {
       otherItem->setPos(pos());
   }
...
   void setOtherItem(Item *item)
   {
      otherItem = item;
   }
private:
   Item *otherItem;
}
Item *item1 = new Item;
Item *item2 = new Item;
item1->setOtherItem(item2);
item2->setOtherItem(item1);
myScene1->addItem(item1);
myScene2->addItem(item2);