Search code examples
pythonqtpysideqwidgetqtabbar

Show close button (x) after hiding it (QTabBar)


I'm creating a method to hide and show the close button of a tab. I found a way to hide it. However, I don't know how to do it in reverse.

This is my existing code for hiding the close button. Using the same lines of codes, how can I show the close button of the tab?

    def disable_close_button(self):
        self.ui.tab_widget.tabBar().setTabButton(self.current_index(), QTabBar.RightSide, None)

    def enable_close_button(self):
        pass

Thanks in advance!


Solution

  • You are not hiding the button, you are eliminating it. So in my solution I get the button and then I hide it or show it as needed.

    import sys
    from PyQt5 import QtCore, QtWidgets
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            show_button = QtWidgets.QPushButton(
                text="show",
                clicked=self.enable_close_button
            )
            hide_button = QtWidgets.QPushButton(
                text="hide",
                clicked=self.disable_close_button 
            )
            self.tab_widget = QtWidgets.QTabWidget(tabsClosable=True)
            for i in range(4):
                label = QtWidgets.QLabel(
                    text="label {}".format(i),
                    alignment=QtCore.Qt.AlignCenter
                )
                self.tab_widget.addTab(label , "tab-{}".format(i))
            lay = QtWidgets.QVBoxLayout(self)
            lay.addWidget(show_button)
            lay.addWidget(hide_button)
            lay.addWidget(self.tab_widget)
    
        @QtCore.pyqtSlot()
        def enable_close_button(self):
            ix = self.tab_widget.currentIndex()
            button = self.tab_widget.tabBar().tabButton(ix, QtWidgets.QTabBar.RightSide)
            if button is not None: 
                button.show()
    
        @QtCore.pyqtSlot()
        def disable_close_button(self):
            ix = self.tab_widget.currentIndex()
            button = self.tab_widget.tabBar().tabButton(ix, QtWidgets.QTabBar.RightSide)
            if button is not None: 
                button.hide()
    
    if __name__ == '__main__':
        app = QtWidgets.QApplication.instance()
        if app is None:
            app = QtWidgets.QApplication(sys.argv)
        app.setStyle("fusion")
        w = Widget()
        w.resize(640, 480)
        w.show()
        sys.exit(app.exec_())