Search code examples
pythonpyqtsignals-slotsqtabwidget

How to prevent a closing tab QTabWidget? PyQT4


With this code:

QtCore.QObject.connect(self.tabWidget, QtCore.SIGNAL("tabCloseRequested(int)"),
                       self.tabWidget.removeTab)

I can close any tab QTabWidget, and the names of these tabs are:

work_1

work_2

work_3

But I want the tab work_1 never closes.

Use Index did not work for two reasons:

  • The tabs can be dynamically moved by this code:

    self.tabWidget.setMovable (True)
    

That makes the Index are constantly changing.

  • The user has the ability to add new tabs.

Solution

  • Tabs can be identified by their widgets, and the widgets can be identified by their objectName (or some other unique attribute):

            self.tabWidget.tabCloseRequested.connect(sef.removeTab)
            ...
    
        def removeTab(self, index):
            widget = self.tabWidget.widget(index)
            if widget is not None and widget.objectName() != 'work_1':
                self.tabWidget.removeTab(index)
    

    or perhaps more simply:

            if widget is not None and widget is not self.work_1:
                self.tabWidget.removeTab(index)