首页 > 解决方案 > 隐藏后显示关闭按钮(x)(QTabBar)

问题描述

我正在创建一种方法来隐藏和显示选项卡的关闭按钮。我找到了隐藏它的方法。但是,我不知道如何反过来。

这是我现有的隐藏关闭按钮的代码。使用相同的代码行,如何显示选项卡的关闭按钮?

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

    def enable_close_button(self):
        pass

提前致谢!

标签: pythonqtpysideqwidgetqtabbar

解决方案


您不是在隐藏按钮,而是在消除它。因此,在我的解决方案中,我得到了按钮,然后根据需要隐藏或显示它。

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_())

推荐阅读