Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

python - How to add items to a QComboBox in PyQt/PySide

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.

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.

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.

That's how I thought of it :

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))

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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.

For example:

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

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.

EDIT

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...