[Interest] QGraphicsScene & removing item
Ch'Gans
chgans at gna.org
Mon Jun 27 06:53:15 CEST 2016
Sorry, have triggered send accidentally:
On 26 June 2016 at 04:40, Igor Mironchik <igor.mironchik at gmail.com> wrote:
> My delete method is:
>
> void
> Form::deleteItems( const QList< QGraphicsItem* > & items )
> {
My feeling is you should try to remove as much logic as possible from
here, there are too many things hapenning in here.
> }
What about something along these lines:
Form::deleteObjects( const QList<FormObject*> &objects)
{
auto command *cmd = new DeleteItemsCommand();
cmd->setItems(...); // Or maybe setObject or setModelItems or ...
model->pushUndoCommand(cmd);
}
DeleteItemsCommand::redo()
{
// Logic here
...
m_model->removeItems(...)
...
}
Model::pushUndoCommand(UndoCommand *command)
{
command->setModel(this); // Tie your command with a model
m_undoStack->push(command); // Will cause QUndoCommand::redo() to be called
}
Model::removeItems()
{
emit aboutToDeleteItems()
// update internal data, sync your stuff
emit itemsDeleted();
}
// connect the model signals to some ad-hoc scene slots
Scene::onModelAboutToDeleteItems(...)
{
// Remove items from scene, maybe using a QMap<ModelItem*, SceneItem*>
// or any other way to associate QGraphicsItem with ModelItems
QList<QGraphicsItem*> items = graphicsItemsForModelItems(...)
QGraphicsScene::removeItems(items);
}
My feeling is that you mix deletion/update/removal of items from both
a model and a QGraphicsScene and on top it's not clear who has
responsability.
Maybe try to clearly separate your data models.
For a 'complex' graphical editor i'm working on, this is exactly what i do:
- UI/Controller generates commands
- commands are executed on a document
- document emit signals similar to what a QAbstractItemModel does
- The scene reacts to document changes and create/update/delete
QGraphicsItem to keep the scene in sync with the document (the model
in my case)
- The QGraphicsView will automatically update the rendering of the scene.
It works like a charm. Requires to write a certain quantity of code
(and unit tests). But at the end it is very efficient, completely
de-coupled, very easy to use, and very reliable (no weird
side-effects).
My 2 cents.
More information about the Interest
mailing list