如何将项目添加到 PyQt/PySide 中的 QComboBox [英] How to add items to a QComboBox in PyQt/PySide

查看:37
本文介绍了如何将项目添加到 PyQt/PySide 中的 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 中的字符串翻译成不同的语言,您应该在创建列表时这样做,并使用 字符串文字.

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)

这篇关于如何将项目添加到 PyQt/PySide 中的 QComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆