How to add items to a combobox in PyQt

前端 未结 3 1795
感动是毒
感动是毒 2020-12-08 19:53

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

相关标签:
3条回答
  • 2020-12-08 20:30

    I had to populate the comboBox using the names from a textfile

    Here's the code:

        names = self.classes_names()
        self.comboBox.addItems(names)
    
        def classes_names(self):
            coconames = CURRENT_DIR + os.sep + 'yolo-coco' + os.sep + 'coco.names'
            with open(coconames) as reader:
                return reader.readlines()
    

    I hope it will help someone in the future.

    0 讨论(0)
  • 2020-12-08 20:36

    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)
    
    0 讨论(0)
  • 2020-12-08 20:46

    There are some simple and easy to read demos/examples here https://github.com/shuge/Enjoy-Qt-Python-Binding ,

    clone it and you will find a demo about how to use basic QComboBox and custom its icon item.

    0 讨论(0)
提交回复
热议问题