问题
I'm trying to make a plot with movable control points usig QGraphicsView
, QGraphicsScene
&& QGraphicsItemGroup
. The problem I've encountered is I can't find any method of removing/deleting the item.
My thoughts are following:
I'm going to have a QGraphicsView, on it are going to be movable interpolation points and under it a plot going through those points is going to be drawn.
To achieve this I'm thinking of using two(or more) QGraphicsItemGroups
.
- one for interpolation points, which cannot be removed since i need to drag them around
- one for the actual plot showing under them
To do that, I'm going to add the Lines into the first group and show them. But there is going to be a lot of redrawing and the thing I don't know right now is HOW TO PROPERLY REMOVE ITEM FROM QGraphicsView
/QGraphicsScene
/QGraphicsItemGroup
so it won't be showing anymore. Please bear in mind that i need to just remove/replace one group of items without removing all the others.
I'm going through the documentation and tutorials but can't find anything useful.
回答1:
You need to start by understanding the Graphics View / Scene system. For example, you state the following:-
"I'm going to have a QGraphicsView, on it are..."
This doesn't make sense. A QGraphicsView is like a window into a world (the QGraphicsScene). So you will be placing items into the scene that are derived from either QGraphicsItem or QGraphicsObject. These are is viewed through a QGraphicsView.
Adding an item is simple, you can just call the QGraphicsScene function addItem, which takes a QGraphicsItem*.
In this case, you have a pointer to the item, so if you call QGraphicsScene::removeItem, it will remove it from the scene and you can then delete the item. If the deletion is to occur inside a slot function, I suggest using the call to deleteLater, rather than a direct delete of the pointer.
Your question mentionsQGraphicsItemGroups. As above, there are the functions QGraphicsScene::createItemGroup and QGraphicsScene::destroyItemGroup.
As the documentation for destroyItemGroup states: -
Reparents all items in group to group's parent item, then removes group from the scene, and finally deletes it
So, in this situation, calling destroyItemGroup will only destroy the group. Therefore, you need to remove and delete the items first, before calling destroyItemGroup.
Note that if you simply delete an item in the scene, it will be removed automatically.
Finally, note that Qt GraphicItems use Qt's parent hierarchy, so you could simply parent objects, rather than using item groups.
来源:https://stackoverflow.com/questions/24910240/properly-removing-items-from-qgraphicsscene-qgraphicsitemgroup-qgraphicsview