You are not logged in.

Dear visitor, welcome to QtForum.org. If this is your first visit here, please read the Help. It explains in detail how this page works. To use all features of this page, you should consider registering. Please use the registration form, to register here or read more information about the registration process. If you are already registered, please login here.

1

Thursday, June 28th 2012, 3:32pm

Python reimplementation of SimpleTreeModel wont load data

I reimplemented the SimpleTreeModel (http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpletreemodel.html) in Python to get to grips with creating trees. I think I mostly get it, but for the life of me I can't figure out why it doesn't load any data. It creates the headers, populates the TreeItem structure, but then none of the data gets displayed.

I used my own data instead of the text example though.
My data is a set of TagSets, each containing a number of tags.
Each tagset/tag has 2 columns, representing Name and ID, both strings.

I am adding standalone example so that the problem can be easily replicated. I'm attaching it also. Apparently "py" is an invalid extension to QtForum so I've renamed and uploaded it as ".txt"

Thanks for any help! I'm sure it's probably the simplest problem causing me such a headache.

Douglas

Source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 27 20:01:55 2012

@author: dpwrussell
"""
from PyQt4 import QtCore, QtGui
import sys


class TreeItem(object):
    def __init__(self, data, parent = None):
        
        self.childItems = []
        self.itemData = data
        self.parentItem = parent

    #Append a child TreeItem to this item
    def appendChild(self, child):
        self.childItems.append(child)
    
    #Get the child at the specified row number
    def child(self, row):
        return self.childItems[row]

    #Get the number of children    
    def childCount(self):
        return len(self.childItems)

    #Get the number of columns for the item    
    def columnCount(self):
        return len(self.itemData)
    
    #Get the data (QVariant) for the specified column of this item
    def data(self, column):
        return self.itemData[column]
    
    #Get the row number of this item (within its parent)
    def row(self):
        # IF it's not the root item
        if (self.parentItem):
            #Return the index of this item
            return self.parentItem.childItems.index(self)
        #Apparently this zero is never used by the model so it's safe despite being the same as the first child
        return 0

    #Get the parent (TreeItem)    
    def parent(self):
        return self.parentItem

class TreeModel(QtCore.QAbstractItemModel):

    def __init__(self, data, parent = None):
        QtCore.QAbstractItemModel.__init__(self, parent)
        #Root Item is the false top-level item, also contains the header information
        self.rootItem = TreeItem([QtCore.QVariant("Name"),QtCore.QVariant("ID")])
        
        self.__setupModelData([], self.rootItem)
        
        print self.rootItem.childCount()
    
    #Get the data (QVariant) for the specified index (QModelIndex) and role
    def data(self, index, role):
        #If the index is not valid
        if not index.isValid():
            #Return an invlalid QVariant
            return QtCore.QVariant()
        
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        
        #Get the actual item using the index
        item = index.internalPointer()
        #Return the data for the specified column
        return item.data(index.column())
    
    #Get flags for the specified index (QModelIndex)
    def flags(self, index):
        #If the index is not valid
        if not index.isValid():
            #Return an invlalid QVariant
            return 0
            
        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
    
    #Get the headerData (QVariant) for the specified section (called section as I guess for different oreintations this is a row or column), orientation and role
    #TODO Temporarily removed default from role (role = QtCore.Qt.DisplayRole())
    def headerData(self, section, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return self.rootItem.data(section)
        return QtCore.QVariant()
    
    #Get index (QModelIndex) of the specified row, column and parent (QmodelIndex)
    def index(self, row, column, parent=QtCore.QModelIndex()):
        #If the model does not have this index
        if not self.hasIndex(row, column, parent):
            return QtCore.QModelIndex()
        
        #First, find the parent
        #If the parent is not valid
        if not parent.isValid():
            #Root is assumed to be the false top-level item
            parentItem = self.rootItem
        else:
            #
            parentItem = parent.internalPointer()
            
        #Second, get the child at the specified row
        childItem = parentItem.child(row)
        
        #Finally, ensure that there was a child
        if childItem:
            #Return a newly created index for that child
            return self.createIndex(row, column, childItem)
        else:
            return QtCore.QModelIndex()

    #Get index of parent (QModelIndex) of index
    def parent(self, index=QtCore.QModelIndex()):
        if not index.isValid():
            return QtCore.QModelIndex()
        
        childItem = index.internalPointer()
        parentItem = childItem.parent()
        
        if parentItem == self.rootItem:
            return QtCore.QModelIndex()
        
        return self.createIndex(parentItem.row(), 0, parentItem)
    
    #Get the number of rows for parent index
    def rowCount(self, parent=QtCore.QModelIndex()):
        #By convention, only column zero has children
        if parent.column > 0:
            return 0

        #If the parent is not valid        
        if not parent.isValid():
            #Set the parent as the rootItem as we want to return the number of top-level items
            parentItem = self.rootItem
        else:
            parentItem = parent.internalPointer()
        
        return parentItem.childCount()
    
    #get the number of columns for parent at index?
    def columnCount(self, parent=QtCore.QModelIndex()):
        #If the parent is not valid  
        if not parent.isValid():
            if parent.internalPointer():
                print "At least it had an internal pointter"
                
            else:
                print "Didn't have an internal pointer"
            #Return the number of columns in the rootItem, I guess this matches up with what rowCount does with the same problem
            return self.rootItem.columnCount()
        else:
            #Return number of columns in the parent
            return parent.internalPointer().columnCount()

    #Creates some dummy data, currently 8 tag sets (0-7) then 2 (0-1)tags as children of those.
    #Tags are numbered with the tagset number then the tag number which is visually unique for easy testing
    #Tagsets are added to the rootItem (parent below)
    # The data parameter does nothing at the moment, as the data is hardcoded    
    def __setupModelData(self, data, parent):        
        
        #5 Tagsets
        for i in range(8):
            tscols = []
            tscols.append(QtCore.QVariant("TagSet" + str(i)))
            tscols.append(QtCore.QVariant("IDTagSet" + str(i)))
        
            tsitem = TreeItem(tscols, parent)
            parent.appendChild(tsitem)
        
            #2 Tags in each
            for j in range(2):
                tcols = []
                tcols.append(QtCore.QVariant("Tag" + str(i) + "-" + str(j)))
                tcols.append(QtCore.QVariant("IDTag" + str(i) + "-" +  str(j)))
                
                titem = TreeItem(tcols, tsitem)
                tsitem.appendChild(titem)
        #Make sure the tree is populated by print to terminal (Seems OK)
        printTree(parent)
        
def printTree(item, tab=""):
    print tab,item.data(0).toPyObject()
    children = item.childItems
    for c in children:
        printTree(c, tab + "\t")
        
        
if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    model = TreeModel([])
    
    #initially verify the tree works by using a predefined model
#    dirsModel = QtGui.QFileSystemModel()
#    dirsModel.setFilter(QtCore.QDir.AllDirs | QtCore.QDir.Dirs | QtCore.QDir.Drives | QtCore.QDir.NoDotAndDotDot)
#    dirsModel.setRootPath("/")
    
    tree = QtGui.QTreeView()
    tree.setModel(model)
    tree.setAnimated(False)
    tree.setIndentation(20)
    tree.setSortingEnabled(True)

    tree.setWindowTitle("Test")
    tree.resize(640, 480)
    tree.show()
    sys.exit(app.exec_())
dpwrussell has attached the following file:

2

Thursday, June 28th 2012, 6:58pm

have you used winpdb? pretty good for python debuging.
If you have a problem, CUT and PASTE your code. Do not retype or simplify it. Give a COMPLETE and COMPILABLE example of your problem. Otherwise we are all guessing the problem from a fabrication where relevant details are often missing.

3

Thursday, June 28th 2012, 8:29pm

have you used winpdb? pretty good for python debuging.
I have tried using pdb in my enviornment, but the problem is that my code never gets called to do anything useful by the tree I set my model to be used in. I suspect I've implemented something wrong in my C to Python conversion but I can't see what.

4

Friday, June 29th 2012, 2:25pm

I have solved the problem.

I had parent.column instead of parent.column()

Sometimes I just hate Python, would never have happened in Java.

5

Friday, June 29th 2012, 6:29pm

yeah, sometimes you can just do too much too easily with python.
If you have a problem, CUT and PASTE your code. Do not retype or simplify it. Give a COMPLETE and COMPILABLE example of your problem. Otherwise we are all guessing the problem from a fabrication where relevant details are often missing.