Keeping track of the "previous" tab index is the only way.
In fact, that's exactly what QTabWidget (or, to be precise, its QTabBar) does: it maintains an internal "current index" property and eventually changes it if the requested one is different, then emits the currentChanged signal.
Since there is no way to access the previous index right before the new one is actually changed, you then need to store it on your own.
One possibility could involve a custom signal that emits the previous index, which you can then connect to a function that eventually calls the required function.
class CustomTabWidget(QTabWidget):
_prevIndex = -1
previousIndexChanged = pyqtSignal(int)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.currentIndexChanged.connect(self.emitPrevIndex)
def emitPrevIndex(self, index):
if self._prevIndex != index:
old = self._prevIndex
self._prevIndex = index
self.previousIndexChanged.emit(old)
def callExitFunction(index):
widget = tabWidget.widget(index)
if widget is not None:
# call the exit function related to that widget
tabWidget.previousIndexChanged.connect(callExitFunction)
You need to be careful and aware about some important aspects, though; specifically:
- if you allow the user to move tabs (or you move them programmatically);
- if new tabs could be inserted before the current tab (using
insertTab() instead of addTab()) at runtime;
- if you allow the possibility of closing tabs, or you remove them (or the related widget is deleted) programmatically;
For all of the above, the _prevIndex attribute may probably become inappropriate or even unused, unless you take proper precautions considering what follows:
- if the tab movement causes the current one to change its index (because a following tab is moved before it or a previous one is moved after the current), the
_prevIndex won't correspond to the current anymore;
- if one of the two moved tab is the current,
currentChanged would be emitted even though no exit function should be called;
- if a new tab is inserted before the current,
_prevIndex will be off by one position;
- the same happens if a tab before the current is removed (or the current one is), but
currentChanged will also be emitted, trying to call the exit function either on a wrong widget, or a non existent one (if the current is the last);
- if the current tab is internally being removed because the widget is deleted, it may cause an exception, depending on what the exit function does;
If you really need runtime/dynamic tab movement/deletion/insertion, you should consider further precautions, possibly adding proper updates to the _prevIndex attribute, and verifying widget existence/index.
currentChangedthen just needs to do e.g.self.tabWidget.widget( self._prev_index).exitFunction(). Can't get much simpler than that.