PyQt5 ListWidget add list items

2019-07-16 04:17发布

问题:

while learning PyQt5 i found a little problem( maybe a bug) in the ListWidget Widget (and all other widgets)

the ListWidget have a addItem method overloaded : ( the code is in c++ but this is the same interface in pyqt )

void    addItem(const QString &label)
void    addItem(QListWidgetItem *item)
void    addItems(const QStringList &labels)

so the problem is that in PyQt5 there is no more QStringList type, and i should use a simple list of strings instead of the QStringList

but when i receive and error telling me that no method match the given paramaters :

Traceback (most recent call last):
  File "main.py", line 21, in <module>
    listWidget.addItem(ls)
TypeError: arguments did not match any overloaded call:
  addItem(self, QListWidgetItem): argument 1 has unexpected type 'list'
  addItem(self, str): argument 1 has unexpected type 'list'

Here is my code :

from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *

import sys


if __name__ == '__main__':

    app = QApplication(sys.argv)


    listWidget = QListWidget()
    listWidget.show()

    ls = ['test', 'test2', 'test3']

    listWidget.addItem('test')
    listWidget.addItem('test2')
    listWidget.addItem('test3')

    listWidget.addItem(ls)

    sys.exit(app.exec_())

回答1:

If you want to add a list you must use the function addItems(). Change:

listWidget.addItem(ls)

to

listWidget.addItems(ls)