PyQt 关闭未选中的标签页

0 投票
1 回答
1554 浏览
提问于 2025-04-19 12:16

为了关闭标签页,我一直在用 QTabWidget.currentWidget() 来找到当前选中的标签页,然后关闭它。但是现在,当我点击另一个标签页上的关闭图标时,它却关闭了当前的标签页,这都是因为我设置的方式。

那么,我该怎么找到和关闭按钮关联的那个标签页,以便能正确地关闭它呢?

谢谢!

1 个回答

4

请使用 void tabCloseRequested (int) 这个方法来处理关闭请求,这样你就可以获取到当前请求关闭的标签页的索引。接下来,可以通过这个索引来找到对应的标签页,使用 QWidget QTabWidget.widget (self, int index) 方法来获取这个标签页,然后将其删除。或者,你也可以使用 QTabWidget.removeTab (self, int index) 方法来移除标签页(不过这样做只是移除标签页的显示,并不会删除实际的页面内容)。

import sys
from PyQt4 import QtGui

class QCustomTabWidget (QtGui.QTabWidget):
    def __init__ (self, parent = None):
        super(QCustomTabWidget, self).__init__(parent)
        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.closeTab)
        for i in range(1, 10):
            self.addTab(QtGui.QWidget(), 'Tab %d' % i)

    def closeTab (self, currentIndex):
        currentQWidget = self.widget(currentIndex)
        currentQWidget.deleteLater()
        self.removeTab(currentIndex)

myQApplication = QtGui.QApplication([])
myQCustomTabWidget = QCustomTabWidget()
myQCustomTabWidget.show()
sys.exit(myQApplication.exec_())

撰写回答