How delete list of actions or 1 among this actions
-
I have a lis of actions
@QList<QAction *> actions = menuRecent_projects->actions();@
How i can delete List or 1 among this actions
I tryed so:@
for(int a=0;a<=actions.count();a++)
delete actions[a];
@And so
@
delete actions[];
@To delete all list
[EDIT: code formatting, Volker]
-
Problem of your for loop is that this list is "live", i.e. if you remove one action, it is automatically deleted out of the list of the actions, thus the list is shortened by one. You can overcome this by counting backwards, as you then only remove from the end and the yet unvisited indices remain stable (supposed you do not have actions inserted twice or more often).
You might want to use "QMutableListIterator":http://doc.qt.nokia.com/4.7/qmutablelistiterator.html if you want to iterate over the list and want to manipulate it in the meantime.
For deleting all actions, just call "qDeleteAll() ":http://doc.qt.nokia.com/4.7/qtalgorithms.html#qDeleteAll-2 on the list.
You must not use your second attempt! delete [] is only allowed for deleting arrays created with new []!
Oh, and a last hint: the list indices are 0-based, so your for loops should look like this:
@
for(int i = 0; i < list.size(); ++i)
@You do "i <= list.size()", which gives you an off by one error (segfault or list assertion).
-
Please note, that Volkers warning that items should only be in the list once if you start to delete them, also goes if you use qDeleteAll()! This will result in -a crash- undefined behaviour:
@
//DON'T DO THIS!!!
QList<QAction*> actionList;
actionList << new QAction();
actionList << actionList.at(0); //re-insert the same item twice...
qDeleteAll(actionList); // BOOM!
@