【问题标题】:Updating PixMaps based on ComboBox selections in PyQt基于 PyQt 中的 ComboBox 选择更新 PixMap
【发布时间】:2020-10-31 18:31:37
【问题描述】:

我有一个 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)

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

【问题讨论】:

  • 欢迎来到 Stackoverflow!为了充分利用网站,提出好的问题很重要。提问指南位于:stackoverflow.com/help/how-to-ask
  • 这是一个不好问的问题吗?
  • 一些你试图避免的例子会很有帮助。然而,它看起来好像你已经吸引了一个答案。再次欢迎!

标签: python combobox pyqt pixmap


【解决方案1】:

您可以对您的代码做一些小的更新,即图像名称(例如,“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 ))

【讨论】:

  • Subin,我已尝试实现此代码,并在我对上面原始帖子的编辑中提供了一个示例。它似乎没有按预期工作。也许我在某个地方犯了一个错误。
  • 没关系,代码的不同部分中还有其他东西导致了问题。这非常有效。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-01-26
  • 2014-06-29
  • 2021-02-04
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 2023-03-09
相关资源
最近更新 更多