Search code examples
qtuser-interfacepyqtqtabwidget

PyQt: proper way to connect QTabWidget.tabCloseRequested to a slot


I've got a simple sample PyQt application with a QTabWidget. I can't connect QTabWidget's tabCloseRequested signal to a slot, so that the tab is closed properly:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Application(object):
    def __init__(self):
        app = QApplication(sys.argv)

        self.window = QMainWindow()

        self.notebook = QTabWidget()
        self.notebook.tabBar().setTabsClosable(True)
        self.notebook.tabBar().setMovable(True)

        self.notebook.tabCloseRequested.connect(self.close_handler)

        self.window.setCentralWidget(self.notebook)

        page1 = QWidget()
        self.notebook.addTab(page1, "page1")
        page2 = QWidget()
        self.notebook.addTab(page2, "page2")

        self.window.show()
        sys.exit(app.exec_())

    def close_handler(self, index):
        print "close_handler called, index = %s" % index
        self.notebook.removeTab(index)

if __name__ == "__main__":
    app = Application()                               

When I click on the close button, nothing happens. Not even the print, which should be invoked! What am I doing wrong?


Solution

  • You need to call setTabsClosable(True) on the tab-widget, rather than its tab-bar:

        self.notebook.setTabsClosable(True)
    

    (PS: the close_handler method is also missing a self argument).