1

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...

4

1 回答 1

3

您正在尝试在尚未创建的 topLevelItem 上设置 Text 。

如果您只想使用 csv 数据填充您的 treeWidget,那么使用构造函数会更容易QTreeWidgetItem(parentWidget, list_of_string)

这样,当您创建项目时,它会作为 topLevelItem 自动添加到 parentWidget,并且您不再需要遍历 csv 行,因为您将它们直接传递给构造函数。

def populate(self):
    with open('Log.csv', 'rt') as f:
        reader = csv.reader(f)
        for row in reader:
            item = QtGui.QTreeWidgetItem(self.treeWidgetLog, row)
于 2013-11-13T09:11:09.107 回答