Search code examples
pythonpyqtqwidgetqtabwidget

How to use QWidget as layout for QTabWidget?


I read that it is possible to use a simple QWidget as Layout for a page of a QTabWidget, so that I can design the tab page the way I want it. How do I implement that?


Solution

  • One of the functionalities of a QWidget is to be a container so it is only necessary to add it in each tab:

    from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
    
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            super().__init__(parent)
            self.tab_widget = QtWidgets.QTabWidget()
            self.setCentralWidget(self.tab_widget)
    
            page1 = QtWidgets.QWidget()
            page2 = QtWidgets.QWidget()
    
            for page, title in ((page1, "Page1"), (page2, "Page2")):
                self.tab_widget.addTab(page, title)
    
            lay1 = QtWidgets.QVBoxLayout(page1)
            for i in range(3):
                lay1.addWidget(
                    QtWidgets.QLabel(f"label{i}", alignment=QtCore.Qt.AlignCenter)
                )
            lay1.addStretch()
    
            lay2 = QtWidgets.QVBoxLayout(page2)
            for i in range(4):
                lay2.addWidget(QtWidgets.QPushButton(f"button {i}"))
            lay2.addStretch()
    
            self.resize(640, 480)
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        sys.exit(app.exec())