سؤال

G'day,

I'm building a multi-window application using PySide and a bunch of QWidgets. I have a QTreeWidget that I would like to populate with the items in a CSV file. The treeWidget has 3 columns (static) and a dynamic number of rows.

I've been filling the QTreeWidget manually up until now, but I'm starting to move from a purely aesthetic to a functioning system. Here's what I've been using:

items = QtGui.QTreeWidgetItem(self.treeWidgetLog)
items.setText(0, "Item 1")
items.setText(1, "Item 2")
items.setText(2, "Item 3")

This only works for adding a single row, but it has been sufficient until now.

I have used csv files with Python extensively in the past, but I'm not sure how to fill the QTreeWidget with entries from the CSV. I've done some research on this, but haven't found anything concrete as of yet. My basic interpretation is this:

with open('Log.csv', 'rt') as f:
    reader = csv.reader(f)
    m = 0
    for row in reader:
        n = 0
        for field in row:
            items.setText(n, field)
            n = n + 1
            return
        m = m + 1

That was just a quick pseudo-script of my intuitive interpretation of a possible solution. I'm not sure how I incorporate the row count (m) in adding rows to the QTreeWidget.

Any ideas?

Thanks!

EDIT: Here's a quick update on what I'm working on:

with open('Log.csv', 'rt') as f:
    reader = csv.reader(f)
    m = 0
    for row in reader:
        n = 0
        for field in row:
            self.treeWidgetLog.topLevelItem(m).setText(n, field)
            n = n + 1
        m = m + 1

However, the above gives me the following error:

AttributeError: 'NoneType' object has no attribute 'setText'

I'm not sure why this is happening, because I've seen topLevelItem().setText() used before...

هل كانت مفيدة؟

المحلول

You're trying to set Text on a topLevelItem which is not yet created.

If you just want to populate your treeWidget using the csv data, the easier would be to use the constructor QTreeWidgetItem(parentWidget, list_of_string).

That way, when you create the item, it is automatically added to the parentWidget as a topLevelItem, and you don't need to iterate over your csv rows anymore since you pass them directly to the constructor.

def populate(self):
    with open('Log.csv', 'rt') as f:
        reader = csv.reader(f)
        for row in reader:
            item = QtGui.QTreeWidgetItem(self.treeWidgetLog, row)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top