Search code examples
pythonpyqt4indexingqcombobox

How to set the default item of a QComboBox


In my function I have dictionary with empty values:

self.items = {
'Maya Executable': '',
'Render': '',
'Mayapy Interpreter': '',
'imgcvt': '',
'IMConvert': '',
}

How should I set "Maya Executable" (i.e. the 0th key) as the QComboBox's default item to be selected when it loads?

I tried:

self.appExeCB=QtGui.QComboBox()
self.appExeCB.setCurrentIndex(0)
self.appExeCB.addItems(self.items.keys())

But this doesn't set the default value :-(


Solution

  • Python Dictionaries are not ordered. self.items.keys()[0] may return different results each time. To solve your problem you should add the items first and then pass the index of 'Maya Executable' from the self.items.keys() to self.appExeCB.setCurrentIndex:

    self.appExeCB=QtGui.QComboBox()
    self.appExeCB.addItems(self.items.keys())
    self.appExeCB.setCurrentIndex(self.items.keys().index('Maya Executable'))
    

    Note that this will not put the items in the QComboBox in the order you declared in self.items because as said before Python Dictionaries are not ordered.