PyQt5 ListWidget add list items

怎甘沉沦 提交于 2020-01-03 19:40:30

问题


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)


来源:https://stackoverflow.com/questions/42682544/pyqt5-listwidget-add-list-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!