GSandro_Strongs
GSandro_Strongs

Reputation: 841

How to populate a QListView with value and display data?

I'm doing a form that contains a QListView. It's populated from database with this code:

model = QStandardItemModel(self.listUser)
for row in self.SELECT_USERS_ACCOUNTS():
    item = QStandardItem(str(row[1]))
    model.appendRow(item)
self.listUser.setModel(model)

My QListView is named listUser and SELECT_USERS_ACCOUNTS() function returns data created by select id,name from table_user, I need to store row[0] (id column in the table_user) too because when the user will click an item into the QListView. I want to capture this Id. Thanks in advance.

Upvotes: 1

Views: 4125

Answers (1)

a_manthey_67
a_manthey_67

Reputation: 4286

In QStandardItem data for different roles can be stored by setData(data, role). Stored data are returned by data(role).

Roles >= 256 (0x100) are UserRoles, see documentation

so you can store the id by

item.setData(row[0],256)

and ask it by

item.data(256) 

edit 31.03.2015:

for row in self.SELECT_USERS_ACCOUNTS():
    item = QStandardItem(str(row[1]))
    # add userData to item
    item.setData(row[0],256)
    # item.setData(row[2], 257) and so on if there are further columns in row
    model.appendRow(item)

self.listUser.setModel(model)
self.listUser.clicked.connect(self.getUserData)

def getUserData(self,index):
    item = self.model().item(index.row(),index.column())
    iId = item.data(256)
    # xyz = item.data(257) for further columns
    print(iId) # or do anything else

Upvotes: 4

Related Questions