Intercept QTabWidget tab change

Viewed 15

I have a widget with multiple tabs in one QTabWidget. The user can make mods to the system and the database within each tab. If the user switches between tabs without saving, all their changes should be lost. I want to give the user a warning before switching tabs, saying that all changes will be lost if a tab is switched. And if the user selects "No", then I want to stay on the current tab.
No matter what I do, the tab is changed to the new one. How do I force the tab widget to stay on the current tab and ignore the tab click? Is there a way to intercept that event and either accept or ignore it?
The code below uses tabBarClicked() event. I assume this is better than currentChanged() since it's probably too late to prevent clicks there.

  def signalsSetup(self):
    self.myTabs.tabBarClicked.connect(self.tabClicked)

  def tabClicked(self, newTabIdx):
    currentIdx = self.myTabs.currentIndex() # The Tab index I am currently on
    if (newTabIdx != 1 and currentIdx == 1 and self.state['madeMods'] == True):
      reply = QMessageBox.question(self, "Tab Change", "Switching tabs before saving will cause unsaved changes to be lost. Continue?", QMessageBox.Yes|QMessageBox.No, QMessageBox.No)
      if reply == QMessageBox.Yes:
        # Some code here to clear edits in the current tab
        # Change tab to new one
        self.myTabs.setCurrentIndex(newTabIdx)
      else:
        # Prevent tab change. Say on current tab
        self.myTabs.setCurrentIndex(currentIdx)
0 Answers
Related