PyQt5 在课堂外添加和删除标签

我有一个 Python 应用程序,它使用 PyQt5 作为它的 GUI。我有一个选项卡小部件,我想在窗口类之外添加和删除选项卡。就像是:


Tabs.addTab("name")

我怎么做?


这是我的代码:


import sys

from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTabWidget ,QVBoxLayout

from PyQt5.QtGui import QIcon

from PyQt5.QtCore import pyqtSlot


class App(QMainWindow):


    def __init__(self):

        super().__init__()

        self.title = 'Test'

        self.left = 0

        self.top = 0

        self.width = 500

        self.height = 500

        self.setWindowTitle(self.title)

        self.setGeometry(self.left, self.top, self.width, self.height)


        self.table_widget = MyTableWidget(self)

        self.setCentralWidget(self.table_widget)


        self.show()


class MyTableWidget(QWidget):


    def __init__(self, parent):

        super(QWidget, self).__init__(parent)

        self.layout = QVBoxLayout(self)


        self.tabs = QTabWidget()

        self.tab1 = QWidget()

        self.tab2 = QWidget()

        self.tabs.resize(300,200)


        self.tabs.addTab(self.tab1, "Tab 1")

        self.tabs.addTab(self.tab2, "Tab 2")


        self.layout.addWidget(self.tabs)

        self.setLayout(self.layout)


if __name__ == '__main__':

    app = QApplication(sys.argv)

    ex = App()

    sys.exit(app.exec_())

谢谢您的帮助!


慕尼黑5688855
浏览 370回答 1
1回答

千万里不及你

无论您要删除类内还是类外的选项卡都没有关系,但您必须使用 QTabWidget 对象,例如在您的情况下,如果您想从“App”类添加一个选项卡,那么您必须这样做它通过属性为“tabs”的对象“table_widget”,即QTabWidget:class App(QMainWindow):&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; super().__init__()&nbsp; &nbsp; &nbsp; &nbsp; # ...&nbsp; &nbsp; &nbsp; &nbsp; self.table_widget.tabs.addTab(QWidget(), "name") # <--- add tab&nbsp; &nbsp; &nbsp; &nbsp; self.table_widget.tabs.removeTab(0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # <--- remove tab
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python