In the example below, which produces this GUI:
… if I click the close button on tab 2 (or tab 3), then on_tab_close
handler fires/is triggered/runs.
However, if I click the button “Close tab 2” which calls .removeTab
, then tab 2 is indeed removed, but the on_tab_close
handler does not fire.
How can I programmatically close tab 2 (here, by clicking the button “Close tab 2”), in a way that will also trigger the on_tab_close
handler?
#!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget, QVBoxLayout, QLabel, QVBoxLayout, QStyle)
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("QTabWidget test")
self.setGeometry(0, 0, 300, 200)
self.cent_widget = QWidget(self)
self.setCentralWidget(self.cent_widget)
self.vlayout = QVBoxLayout(self.cent_widget)
self.close_btn = QPushButton("Close tab 2")
self.close_btn.clicked.connect(self.on_close_btn)
self.vlayout.addWidget(self.close_btn)
self.tabswidget = QTabWidget()
self.vlayout.addWidget(self.tabswidget)
self.tab1 = QLabel("This is tab 1.")
self.tab2 = QLabel("This is tab 2.")
self.tab3 = QLabel("This is tab 3.")
self.tabswidget.addTab(self.tab1, "Tab 1")
self.tabswidget.addTab(self.tab2, "Tab 2")
self.tabswidget.addTab(self.tab3, "Tab 3")
self.tabswidget.setTabsClosable(True) # /q/60409663
default_side = self.tabswidget.style().styleHint(
QStyle.SH_TabBar_CloseButtonPosition, None, self.tabswidget.tabBar()
)
self.tabswidget.tabBar().setTabButton(0, default_side, None)
self.tabswidget.tabCloseRequested.connect(self.tabswidget.removeTab) # /q/19151159
self.tabswidget.tabCloseRequested.connect(self.on_tab_close)
self.show()
def on_close_btn(self):
print("on_close_btn")
self.tabswidget.removeTab( self.tabswidget.indexOf(self.tab2) )
def on_tab_close(self):
print("on_tab_close")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyWindow()
sys.exit(app.exec_())