1

我有一个填充有文本条目的 QComboBox(例如,“apple”、“orange”、“banana”)。I need to update a QPixMap located in a cell of a gridlayout whenever one of the listed items is selected. 因此,如果您选择“apple”,apple.jpg 将显示在指定的 ComboBox 的 PixMap 单元格中。

我试图避免在代码中手动输入一长串“if/else”语句,因为我将有许多带有多个选项的组合框(最终来自数据库队列)和许多图像单元格(每个组合框一个)。

在网格内的 QLabel 容器中创建静态 PixMap,我可以处理。以及组合框本身。

编辑:

我试图实现 Subin Gopi 建议的代码(我只包含了相关部分):

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)

这似乎不允许图像更新。不知道我只是在某个地方犯了一个公然的错误还是什么。

4

1 回答 1

0

你可以对你的代码做一些小的更新,即图像名称(例如,“apple”、“orange”、“banana”)和 QComboBox 项目名称应该相同。所以你可以避免 if else 语句。检查示例代码。

QComboBox.currentIndexChanged.connect (imageUpdate)
imagePath       = 'C:/images'

def imageUpdate :
    currentItem     = str (QComboBox.currentText ())
    currentImage    = '%s/%s.jpg'% (imagePath, currentItem) 
    QLabel.setPixmap (QtGui.QPixmap (currentImage ))
于 2017-01-20T06:11:00.923 回答