Python – Qcombobox in PyQt, how to set options in one combo box based on the choice of other combo boxes?

Qcombobox in PyQt, how to set options in one combo box based on the choice of other combo boxes?… here is a solution to the problem.

Qcombobox in PyQt, how to set options in one combo box based on the choice of other combo boxes?

For example, the first combo box with option A and option B.
If I select option A in the first combo box, the second combo box contains options 1, 2, 3, 4, 5.
If I select option B in the first combo box, the second combo box contains options a, b, c, d, e.

How can I do this in PyQt5? I searched for the Qcombobox class and there are 2 classes activated and currentIndexChanged, but don’t know which one I need to use in PyQt5 and how to use it.

Solution

I’ll do it :

import sys
from PyQt5 import QtWidgets

class ComboWidget(QtWidgets.QWidget):

def __init__(self, parent=None):
        super(ComboWidget, self).__init__(parent)
        self.setGeometry(50, 50, 200, 200)

layout = QtWidgets.QVBoxLayout(self)

self.comboA = QtWidgets.QComboBox()
        # The second addItem parameter is itemData, which we will retrieve later
        self.comboA.addItem('A', ['1', '2', '3', '4'])
        self.comboA.addItem('B', ['a', 'b', 'c', 'd', 'e'])
        self.comboA.currentIndexChanged.connect(self.indexChanged)
        layout.addWidget(self.comboA)

self.comboB = QtWidgets.QComboBox()
        # We could have added the 1,2,3,4 items directly, but the following
        # is a bit more generic in case the combobox starts with a different
        # index for some reason:
        self.indexChanged(self.comboA.currentIndex())
        layout.addWidget(self.comboB)

self.show()

def indexChanged(self, index):
        self.comboB.clear()
        data = self.comboA.itemData(index)
        if data is not None:
            self.comboB.addItems(data)

def main():
    app = QtWidgets.QApplication(sys.argv)
    w = ComboWidget()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

This way, your code is more forward-looking, because it makes it very easy to add/modify/remove items from any drop-down menu if you want to add/modify/remove items at some point.

Related Problems and Solutions