I have a class MainWindow
derived from QMainWindow
class MainWindow : public QMainWindow
{
Q_OBJECT
private:
struct MetaObra
{
InterfazObra* miobra;
QString nombrefichero;
MetaObra():miobra(nullptr){}
};
std::list<MetaObra>ListaObras;
std::list<MetaObra>::iterator obraActual;
.........................
}
When I add an element of the type MetaObra to the list, a tab of a QTabWidget
appears. When I change the active tab the iterator points to the MetaObra of the list .... up there everything is fine.
The problem I have when closing tabs, if I close a tab that is not the last, the iterator goes to the next tab, but when I want to close that, the program fails and closes.
This would be the code to close the tabs:
void MainWindow::ActionCerrar()
{
std::list<MetaObra>::iterator obraBorrar = obraActual;
if (ListaObras.size()>1)
{
if (obraActual!=ListaObras.end() && std::next(obraActual)==ListaObras.end())//ultimo elemento
{
obraActual=std::prev(obraActual);
}
else
{
obraActual=std::next(obraActual);
}
}
delete obraBorrar->miobra;
ListaObras.erase(obraBorrar);
}
What I do first is check if there is more than one item in the list. If so, I check if it's the last one. If it is the last one, I put the iterator in the previous element. If it is not, I put it in the next element. Then proceed to delete the contents of the pointer and finally remove the item from the list. I have checked the behavior and it is correct.
Imagine that I have 3 works, one in each tab.Obra1, Obra2, Obra3. If I close the tab of the Obra2, Obra3 is set as an active tab. If I close it then, the program fails. However, if before closing the tab change to Obra1 as active tab and then return to Obra3, it closes normally. When I close the tabs in decreasing order there are no problems, but if I close them from "left to right"