Search code examples
pythonpython-3.xpyqtpyqt5qlistwidget

How to insert Items from a list into QlistWidget?


I want to insert a list of items into a QlistWidget. Below is the code i am using:

names = ['apple', 'banana', 'Cherry']
for item in names:
   self.listWidget.insertItems(item)

But i am having an error that below :

TypeError: insertItems(self, int, Iterable[str]): argument 1 has unexpected type 'str'

Please let me know the issue is.


Solution

  • If you check the docs:

    void QListWidget::insertItems(int row, const QStringList &labels)

    Inserts items from the list of labels into the list, starting at the given row.

    It is observed that the method X needs to have the initial position from where it will be inserted, so when not giving information where you want to add it will show 2 solutions:

    add at start:

    self.listWidget.insertItems(0, names)
    

    add it at the end:

    self.listWidget.insertItems(self.listWidget.count(), names)
    

    For the last case it is better to use the addItems() method:

    self.listWidget.addItems(names)