Remove tabs from QTabWidget when current index changed
-
Hello !
I have an application managing a file editor with
QTabWidget
, and when the current index changed, I check that the opening file still exists on the disk, and if not, I ask the user if we wants to keep the file in the editor.
If he chooses to remove it, then it changes the tab again, so all tabs can be closed like this.The problem is that I have a crash if all files are closed each time the current index changes.
Here is the standalone code to reproduce it:#include <QApplication> #include <QTabWidget> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTabWidget tab; tab.addTab(new QWidget, "1"); tab.addTab(new QWidget, "2"); tab.addTab(new QWidget, "3"); QObject::connect(&tab, &QTabWidget::currentChanged, [&tab](int index) { if (index == -1) { return; } // [2] // We imagine that it cheks that the file is not on the disk anymore, // and we asked the user for removing the associated tab. QWidget *tabWidget = tab.widget(index); if (tabWidget) { tab.removeTab(index); // currentChanged is emitted and the slot is called again here! tabWidget->deleteLater(); } }); tab.show(); // [1] Try to remove all tabs while (tab.count() > 0) { QWidget *tabWidget = tab.widget(0); if (tabWidget) { tab.removeTab(0); tabWidget->deleteLater(); } } return a.exec(); }
At [1], I simulate a "close all files" action, but at the first iteration, they all are prematurely removed by
currentChanged
slot at [2].
The crash happens inside theremoveTab
function in the lambda. Each time we switch to a new tab, the current function pauses at removeTab and we have 3 executions ofremoveTab
in the stack. When we come back, it's like Qt is not able to finish the execution ofremoveTab
.Thanks for your help!!
-
@Maluna34 said in Remove tabs from QTabWidget when current index changed:
The rule is not to emit a signal from the triggered slot, is that it?
correct
I tried with a dedicated slot, it also seems to solve the problem.
I doubt so - there is no difference of a member function or a lambda here