pythoncomboboxpyqtpixmap

Updating PixMaps based on ComboBox selections in PyQt


I have a QComboBox populated with text entries (e.g., "apple", "orange", "banana"). I need to update a QPixMap located in a cell of a gridlayout whenever one of the listed items is selected. So, if you select "apple", the apple.jpg would display within the specified ComboBox's PixMap cell.

I was trying to avoid a long list of manually entered "if/else" statements in the code because I am going to have many combo boxes with several options (eventually from database queues) and many image cells (one for each combo box).

Creating static PixMaps in QLabel containers within the grid, I can handle. As well as the ComboBoxes themselves.

Edit:

I have tried to implement the code suggested by Subin Gopi (I have only included relevant sections):

self.fruit_list = ['apple', 'orange', 'banana']

self.fruit_combo = QtGui.QComboBox()
self.fruit_combo.addItems(self.fruit_list)

def image_update(self, qcombobox, qlabel):
    image_path ="c :/images"
    current_item = str(qcombobox.currentText())
    current_image = '%s/%s.jpg' %(image_path, current_item)
    qlabel.setPixmap(QtGui.QPixmap(current_image))

self.fruit_image = QtGui.QLabel(self)
self.grid.addWidget(self.fruit_image, 1, 1) 
self.fruit_combo.currentIndexChanged[str].connect(lambda: 
                  self.image_update(self.fruit_combo, self.fruit_image)

This doesn't seem to be allowing the image to update. Not sure if I am just making a blatant mistake somewhere or what.


Solution

  • You can do one small updates on your code, that is image name (e.g., "apple", "orange", "banana") and QComboBox item name should be same. So you can avoid if else statements. Check the example code.

    QComboBox.currentIndexChanged.connect (imageUpdate)
    imagePath       = 'C:/images'
    
    def imageUpdate :
        currentItem     = str (QComboBox.currentText ())
        currentImage    = '%s/%s.jpg'% (imagePath, currentItem) 
        QLabel.setPixmap (QtGui.QPixmap (currentImage ))