[英]QT 5.6: Segmentation violation in second call to QGraphicsScene::addItem()
[英]qt QGraphicsScene additem
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.