我需要一些帮助来添加一些项目到 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)
这篇关于如何在 PyQt/PySide 中将项目添加到 QComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何将函数绑定到 Qt 菜单栏中的操作?How to bind a function to an Action from Qt menubar?(如何将函数绑定到 Qt 菜单栏中的操作?)
PyQt 启动后进度跃升至 100%PyQt progress jumps to 100% after it starts(PyQt 启动后进度跃升至 100%)
如何将 yaxis 刻度标签设置在固定位置,以便当我How to set yaxis tick label in a fixed position so that when i scroll left or right the yaxis tick label should be visible?(如何将 yaxis 刻度标签设
`QImage` 构造函数有未知关键字 `data``QImage` constructor has unknown keyword `data`(`QImage` 构造函数有未知关键字 `data`)
将 x 轴刻度更改为自定义字符串Change x-axis ticks to custom strings(将 x 轴刻度更改为自定义字符串)
如何在python中将文件保存为excel时显示进度条?How to show progress bar while saving file to excel in python?(如何在python中将文件保存为excel时显示进度条?)