PDA

View Full Version : PyQt4 tree model



MTK358
23rd February 2011, 14:51
class BrickListModel(QAbstractItemModel):

def __init__(self):
QAbstractItemModel.__init__(self)

self.bricks = []

def addBrick(self, brick):
self.beginInsertRows(QModelIndex(), len(self.bricks), len(self.bricks))
self.bricks.append(brick)
self.endInsertRows()

def removeBrick(self, index):
self.beginRemoveRows(QModelIndex(), index, index)
del self.bricks[index]
self.endRemoveRows()

def clearBricks(self):
if len(self.bricks) != 0:
self.beginRemoveRows(QModelIndex(), 0, len(self.bricks) - 1)
self.bricks = []
self.endRemoveRows()

def getAllBricks(self):
return self.bricks

def index(self, row, column, parent):
if not parent.isValid():
if column < 2:
if row > len(self.bricks):
return createIndex(row, column)
return QModelIndex()

def rowCount(self, parent):
return len(self.bricks)

def columnCount(self, parent):
return 2

def data(self, index, role):
if index.column == 0:
return self.bricks[index.row()]['id']
elif index.column == 1:
return self.bricks[index.row()]['comment']
return QVariant()

def parent(self, index):
return QModelIndex()

def headerData(self, section, orientation, role):
if section == 0:
return "Brick"
if section == 1:
return "Comment"
return QVariant()

I am using a tree view instead of a list view because I want to have multiple columns.

The problem is that no items show up in the view. What's the problem?

norobro
23rd February 2011, 21:54
Some comments for you to try:


def index(self, row, column, parent):
if not parent.isValid():
# if column < 2: // The model has a columnCount function
# if row > len(self.bricks): // When will this ever be true?
return createIndex(row, column)
return QModelIndex()

def data(self, index, role):
if(role == Qt.DisplayRole): // add - only return data for display role
if index.column() == 0: // add () after column
return self.bricks[index.row()]['id']
elif index.column() == 1: // add () after column
return self.bricks[index.row()]['comment']
return QVariant()
HTH

MTK358
24th February 2011, 02:18
It kind of works now, but the header is not shown and there is an arrow (like the one to view the item's children) on each line.

norobro
24th February 2011, 03:00
Try putting the following in headerData():
if(orientation == Qt.Horizontal and role == Qt.DisplayRole):


... there is an arrow (like the one to view the item's children) on each line.Check out QTreeView::rootIsDecorated()

BTW, I didn't mean to put the angry emoticon in the title of my first post.

MTK358
24th February 2011, 14:27
It works great now!