qt 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);
相关文章:
- Qt 错误:错误:调用"QHBoxLayout::addItem(QPushButton*&)"没有匹配函数
- QT 5.6:对QGraphicsScene::addItem()的第二次调用中出现分段冲突
- Qt QListWidget addItem内存泄漏
- CMFCToolBarComboBoxButton中的AddItem-不显示新值
- Qt中的错误:QMainWindowLayout::addItem:请改用公共QMainWindow API
- QMetaObject::invokeMethod()在用于调用QListWidget::addItem()时返回fal
- QGraphicsScene::addItem:项已添加到此场景中
- Memoryleak with QListWidget addItem() + setItemWidget()
- qt QGraphicsScene additem