简体   繁体   中英

Reading .csv file in qlistWidget in pyQt

I have written the following code:

import sys
from PyQt4.QtGui import *
import csv

reader = csv.reader(open('/home/Desktop/elements.csv'))

fx_elements = {}
for row in reader:
    key = row[0]
    if key in fx_elements:
        # implement your duplicate row handling here
        pass
    fx_elements[key] = row[1:]
list = sorted(fx_elements.keys())
#print list

app = QApplication(sys.argv)
listWidget = QListWidget()
listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
#item = listWidget.QListWidgetItem('elements')
#listWidget.insertItem(list)
listWidget.show()
sys.exit(app.exec_()) 

Everything above works fine, except that the listWidget doesn't append the list I have in my csv file

How do i add items from csv file in my qlistWidget . also my csv file have elements separated using , .

Please help

First of all, do not use list as a variable name, that shadows the list() built-in function , and then later on you would not be able to use list() to create lists.

To append to a QListWidget , you need to create QListWidgetItem and add it to the the widget, you can do a similar code -

lst = sorted(fx_elements.keys())
app = QApplication(sys.argv)
listWidget = QListWidget()
listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
for k in lst:
    item = QListWidgetItem(k)
    listWidget.addItem(item)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM