In this tutorial, we will learn how to create dependent combo box with PyQt5 in Python.
A combo box (some people called it drop-down) is a graphical control allowing a user to pick an item from a list. Often time, there will be scenario where you want to specify a combo box list depending on a parent value. So in this tutorial, I will walk you through the steps to create a dependent combo box using PyQt5.
Buy Me a Coffee? Your support is much appreciated!
PayPal Me: https://www.paypal.me/jiejenn/5
Venmo: @Jie-Jenn
Source Code:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QHBoxLayout
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QFont
class AppDemo(QWidget):
def __init__(self):
super().__init__()
self.setFixedSize(700, 100)
mainLayout = QHBoxLayout()
self.model = QStandardItemModel()
# states
self.comboStates = QComboBox()
self.comboStates.setFixedSize(325, 50)
self.comboStates.setFont(QFont('', 12))
self.comboStates.setModel(self.model)
# cities
self.comboCities = QComboBox()
self.comboCities.setFixedSize(325, 50)
self.comboCities.setFont(QFont('', 12))
self.comboCities.setModel(self.model)
# add data
for k, v in data.items():
state = QStandardItem(k)
self.model.appendRow(state)
for value in v:
city = QStandardItem(value)
state.appendRow(city)
self.comboStates.currentIndexChanged.connect(self.updateStateCombo)
self.updateStateCombo(0)
mainLayout.addWidget(self.comboStates)
mainLayout.addWidget(self.comboCities)
self.setLayout(mainLayout)
def updateStateCombo(self, index):
indx = self.model.index(index, 0, self.comboStates.rootModelIndex())
self.comboCities.setRootModelIndex(indx)
self.comboCities.setCurrentIndex(0)
data = {
'California': ['San Francisco', 'Oakland', 'Los Angeles'],
'Illinois': ['Chicago', 'Springfield', 'Evanston'],
'Texas': ['Austin', 'Houston', 'San Antonio']
}
app = QApplication(sys.argv)
demo = AppDemo()
demo.show()
sys.exit(app.exec_())