Search code examples
pythoncsvpyqtpyqt5qcombobox

How to fill a QComboBox with elements from a CSV file


I have a combobox on a QTDesigner QDialog form that I would like to fill with a the contents of a column in a CSV file. I invoke the call for the combo box and have the function built to pull the values from the CSV, but the combo box will not update with the information.

self.optStates.currentIndexChanged.connect(self.selectState)
def selectState(self):
    with open('States.csv') as csvDataFile:
        csvReader = csv.DictReader(csvDataFile, delimiter=',')
        states = []
        states.extend([row['state'] for row in csvReader if row['state']])

The other code has been omitted, but the rest of the dialog works fine.


Solution

  • currentIndexChanged is a signal that is triggered when you choose an option of the QComboBox and since there is no item in your QComboBox it will never fire, besides there is no need to use it in this case. What you must do is fill it in the constructor using the addItems() method

    def __init__(self, another_arguments):
        # 
        # some code
        # 
        with open('States.csv') as csvDataFile:
            csvReader = csv.DictReader(csvDataFile, delimiter=',')
            states = [row['state'] for row in csvReader if row['state']]
            self.optStates.addItems(states)