how to store and retrieve custom data (using QtCore.Qt.UserRole?) with Qtableview /QAbstractTableModel in pyqt?

MrX picture MrX · Jan 13, 2015 · Viewed 9.2k times · Source

I'm quite new in the use of model/view framework and I'm having some trouble, I'm using a Qtableview and a QAbstractTableModel on a widget and I'm trying to store some custom data in the QModelIndex using the "data" method from the QAbstractTableModel , something like this:

class myTableModel(QtCore.QAbstractTableModel):

def __init__(self, parent = None):
    QtCore.QAbstractTableModel.__init__(self, parent)
    self.elements = [[this is supposed to be initialized at some point]] 

def rowCount(self, parent = QtCore.QModelIndex()):
    return len(self.elements)

def columnCount(self, parent = QtCore.QModelIndex()):
    return len(self.elements[0])

def data(self, index, role = QtCore.Qt.DisplayRole):
    row = index.row()
    col = index.column()
    if role == QtCore.Qt.DisplayRole:
        return self.elements[row][col].getName()# an string gets stored and displayed on the widget
    if role == QtCore.Qt.UserRole: 
        return self.elements[row][col]

But I cannot make it to work: I've been able to retrieve successfully the name , but not the object . ..

After some messing around including printing the "role" arg of the data method to see which roles are passed to the method ( I got 0,6,7,10 ... but not 32 or other roles ) and taking a look to the docs, it seems that only some roles ( not "QtCore.Qt.UserRole") are available during the call to "data" method?

Is there a way of achieving this using "QtCore.Qt.UserRole"? I've read that this can be achieved using delegates? how exactly? and if not, how could I go about it?

Thanks a lot!, X

Answer

three_pineapples picture three_pineapples · Jan 14, 2015

Your data method signature appears incorrect. It should be data(self, index, role = QtCore.Qt.DisplayRole)

Based on the code provided, you should be able to call myModel.data(index, QtCore.Qt.UserRole) to get what you want. As you have pointed out, QtCore.Qt.UserRole is just an integer. If you pass the integer to the role keyword argument of the data() method, then your code will return self.elements[row][col].

There is nothing special or magical about the UserRole. It's just an integer that has been put aside for generic use. See the documentation for the list of roles. Note that Qt is not going to access this data by itself. The UserRole is there for you, not Qt.

If you want the data stored in the UserRole to be used in a view (I assume that's why you have mentioned delegates?), then you will need to provide a specific example of such data, the view, the model and how you want the data to be used. I would recommend posting a new question if that is what you are looking for.