Search code examples
pythonpyqtpyqt5qtabwidgetqcheckbox

Dynamically insert checkboxes into a tabWidget


I am building a small application using pyQt5. Till now I've built a UI using QtCreator, converted that to a Python file using pyuic and now on the push of a button, it should dynamically populate the tabWidget's tabs with checkboxes having labels pulled from a string list. I can't seem to figure out the best way to go about this problem.

Till now I've done the following.

  1. Link the UI file with my main python code.
  2. Handle a button click to call a function to insert checkboxes.
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.auth_select.clicked.connect(self.handle_auth)
        self.show()
    def populate_tabs(self):
        self.tabWidget.addWidget(QtWidgets.QCheckBox())

I cannot seem to figure out how to dynamically insert the checkboxes into a certain tab. Let's say my tab name is main_tab; I want to insert 5 checkboxes whose labels and ids come from 2 lists labels[] and ids[].


Solution

  • Alright, for anyone who stumbles upon this. I went about this as described below.

    1. Create a layout to house inner elements
    2. Dynamically insert QWidgets into this layout
    3. Finally set the layout of the tab/widget you need to, to the above.

    A small example is [extended from above]

    class MainWindow(QMainWindow, Ui_MainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            self.setupUi(self)
            self.auth_select.clicked.connect(self.handle_auth)
            self.show()
            self.populate_tabs(connection_string)
        def populate_tabs(self, connection_string):
            layout = QGridLayout()
            for i in range(1, 5):
                for j in range(1, 10):  
                    layout.addWidget(QCheckBox("Check #{}".format(i)) , i, j)
    
            self.tabWidget.widget(2).setLayout(layout)