如何在 PyQt/PySide 中将项目添加到 QComboBox

2022-01-12 00:00:00 python pyqt pyside pyqt5 qcombobox

问题描述

我需要一些帮助来添加一些项目到 QComboBox.所以我有两个组合框,一个根据所选项目填充另一个.

I need some help adding some items to a QComboBox. So I have two comboboxes, and one populates the other depending on the item selected.

我的问题是,将 additem 用于新项目,它可以工作,但如果我为组合框选择另一个选项,它会添加新项目,但以前的项目已经消失 - 而且有新项目下方的空白项目.

My question is that, using additem for new items, it works, but if I choose another option for the combobox, it adds the new items, but the previous items are gone - and there are blank items below the new ones.

我以为每次我从第一个组合框中选择一个新选项来清除第二个组合框的内容.所以我在第二个中使用了 clear() - 但它不起作用.

I thought that each time I chose a new option from the first combobox to clear the contents of the second combobox. So I used the clear() on the second - but it didn't work.

我是这么想的:

self.comboBox_2.clear()
for index,i in enumerate(list1):
  self.comboBox_2.addItem(_fromUtf8(""))
  self.comboBox_2.setItemText(index+2, QApplication.translate("Dialog", i, None, QApplication.UnicodeUTF8))

以上是当第一个combobox改变时执行的函数的一部分.

The above is part of a function that executes when the first combobox changes.


解决方案

假设 list1 是一个字符串列表,那么您可以简单地使用 addItems 方法:

Assuming list1 is a list of strings, then you can simply add them all at once using the addItems method:

self.comboBox_2.clear()
self.comboBox_2.addItems(list1)

请注意,您可能在示例中以错误的方式使用了 QApplication.translate.如果您想让 list1 中的字符串可以翻译成不同的语言,您应该在 create 列表时这样做,并使用 字符串字面量.

Note that you are probably using QApplication.translate in the wrong way in your example. If you want to make it possible for the strings in list1 to be translated into a different language, you should do that when you create the the list, and use string literals.

例如:

list1 = [
    self.tr('First Item'),
    self.tr('Second Item'),
    self.tr('Third Item'),
    ]

另请注意,_fromUtf8 函数只有在您的代码中使用包含非 ascii 字符的字符串文字时才真正有用 - 否则,它基本上是无操作的.

Also note that the _fromUtf8 function is only really useful if you're using string literals containing non-ascii characters in your code - otherwise, it's basically a no-op.

编辑

如果您的列表包含像素图和文本的元组,那么您可以使用以下内容:

If your list contains, say, tuples of pixmaps and text, then you can use something like this:

self.comboBox_2.clear()
for pixmap, text in list1:
    self.comboBox_2.addItem(QIcon(pixmap), text)

相关文章