Spatial Digger
Spatial Digger

Reputation: 1993

PyQt5 combo retrieve the value rather than the key or text

In my class definition I have:

    colours = {
        None: None,
        "Red": "255,0,0",
        "Green": "0, 255, 0",
        "Blue": "0, 0, 255",
    }

    self.colourComboTop.addItems(colours)

In my code:

def some_function(self):

    self.colourComboTop.currentIndex()

Gets the index, 0, 1, 2, 3

    self.colourComboTop.itemText(self.colourComboTop.currentIndex())

Gets the displayed text.

How do I access the value associated with the key? So with {"Red": "255,0,0"} I want the rgb value as a string.

Upvotes: 0

Views: 51

Answers (1)

alec
alec

Reputation: 6112

Either set the RGB value as the userData argument,

for key, value in colours.items():
    self.colourComboTop.addItem(key, value)

key = self.colourComboTop.currentText()
rgb = self.colourComboTop.currentData()

Or keep a reference to the dict and just map it.

self.colours = {
    None: None,
    "Red": "255,0,0",
    "Green": "0, 255, 0",
    "Blue": "0, 0, 255",
}

self.colourComboTop.addItems(self.colours)

key = self.colourComboTop.currentText()
rgb = self.colours[key]

Upvotes: 1

Related Questions