14

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 :-(

ekhumoro
  • 115,249
  • 20
  • 229
  • 336

2 Answers2

13

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.

YusuMishi
  • 2,317
  • 1
  • 18
  • 8
  • Beware ! The order of the keys from a python dict is not guaranteed to be stable. you need to keep the result of the first call to self.items.keys() and use this specific list. Calling again self.items.keys() might produce the same keys sorted differently. – LBarret Jan 19 '14 at 16:35
3

There are a couple of things wrong with your code.

Firstly, dictionaries have no fixed order, so the keys won't necessarily end up in the same order that they were inserted in:

>>> items = {
...     'Maya Executable': '',
...     'Render': '',
...     'Mayapy Interpreter': '',
...     'imgcvt': '',
...     'IMConvert': '',
...     }
>>> items.keys()
['Mayapy Interpreter', 'IMConvert', 'imgcvt', 'Render', 'Maya Executable']

So "Maya Executable" isn't the first item in the list of keys.

Secondly, you are trying to set the current index before adding the items, when you should be setting it afterwards. As it is, the combo-box will just default to showing the first item, which would be "Mayapy Interpreter".

EDIT:

If you use an OrderedDict, your example code should work as expected:

from collections import OrderedDict
...
self.items = OrderedDict([
    ('Maya Executable', ''),
    ('Render', ''),
    ('Mayapy Interpreter', ''),
    ('imgcvt', ''),
    ('IMConvert', ''),
    ])
self.appExeCB.addItems(self.items.keys())

(NB: Python >= 2.7 is required for OrderedDict)

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • 1
    yes but how does Maya Interpreter turns out to be the first item(i.e the 0th item) –  Dec 08 '12 at 18:57
  • @san. A dictionary is a *mapping* with no fixed order. If you want a fixed order, you could use an [OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict). – ekhumoro Dec 08 '12 at 19:00
  • 1
    guess i cannot use it because i am bound to python 2.6 –  Dec 08 '12 at 19:25