简体   繁体   中英

How to add a stacked layout in a tab widget in PyQt5?

I am trying to add multiple tables to a single tab of the QTabWidget with the help of QStackedLayout. Here is my code:

class ui(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('ui')

        self.generalLayout = QGridLayout()
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        self._centralWidget.setLayout(self.generalLayout)
        self.table()

    def table(self):
        self.tabs_layout = QTabWidget()
        self.stack_layout = QStackedLayout()

        self.display1 = QTableWidget()
        self.display1.setColumnCount(2)
        self.display1.setHorizontalHeaderLabels(['S. No.', 'Title'])
        self.header = self.display1.horizontalHeader()
        self.header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.header.setSectionResizeMode(1, QHeaderView.Stretch)

        self.display2 = QTableWidget()
        self.display2.setColumnCount(2)
        self.display2.setHorizontalHeaderLabels(['S. No.', 'Name'])
        self.header = self.display2.horizontalHeader()
        self.header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.header.setSectionResizeMode(1, QHeaderView.Stretch)

        self.stack_layout.addWidget(self.display1)
        self.stack_layout.addWidget(self.display2)

        self.tabs_layout.addTab(self.stack_layout,'1')
        self.generalLayout.addWidget(self.tabs_layout,0,0)

Executing the above mentioned code I am getting the following error:

Traceback (most recent call last):
  File "ui.py", line 52, in <module>
    main()
  File "ui.py", line 44, in main
    window = ui()
  File "ui.py", line 15, in __init__
    self.table()
  File "ui.py", line 38, in table
    self.tabs_layout.addTab(self.stack_layout,'1')
TypeError: arguments did not match any overloaded call:
  addTab(self, QWidget, str): argument 1 has unexpected type 'QStackedLayout'
  addTab(self, QWidget, QIcon, str): argument 1 has unexpected type 'QStackedLayout'

Is there any way to resolve this issue?

QTabWidget.addTab excepts a widget as its first argument but you are supplying a layout. To get around this you could initialize a QWidget , set its layout to self.stack_layout and add this widget to self.tabs_layout instead of self.stack_layout . ie in table(self) , replace self.tabs_layout.addTab(self.stack_layout,'1') with something like

tab = QWidget()
tab.setLayout(self.stack_layout)
self.tabs_layout.addTab(tab,'1')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM