Dqu1J
Dqu1J

Reputation: 37

PyQt5 Add and remove tabs outside of class

I have a Python app that uses PyQt5 for it's GUI. I have a Tab Widget in it, and I want to add and remove tabs outside of window class. Something like:

Tabs.addTab("name")

How do I do that?

Here is my code:

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

Thank you for your help!

Upvotes: 1

Views: 2664

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

It does not matter if you are going to remove the tab within the class or outside of it but you have to use the QTabWidget object, for example in your case if you want to add a tab from the "App" class then you must do it through the object "table_widget" whose attribute is "tabs" which is the QTabWidget:

class App(QMainWindow):
    def __init__(self):
        super().__init__()
        # ...
        self.table_widget.tabs.addTab(QWidget(), "name") # <--- add tab
        self.table_widget.tabs.removeTab(0)              # <--- remove tab

Upvotes: 2

Related Questions