Can I store some user data in every item of a QListWidget?
Asked Answered
W

2

24

I want to store some filenames in a QListWidget. I need to have the full file paths, but I only want to show the base filename. I probably could store the full filename in the tooltip for each item, but I'd rather not have tooltips for the list items.

Wellbred answered 21/8, 2011 at 6:39 Comment(0)
S
39

You can set data for and get data from each QListWidgetItem. See QListWidgetItem::setData() and QListWidgetItem::data(). Data can be set for different roles. Use Qt::UserRole, which is "The first role that can be used for application-specific purposes."

Try something like this:

QListWidgetItem *newItem = new QListWidgetItem;
QString fullFilePath("/home/username/file");
QVariant fullFilePathData(fullFilePath);
newItem->setData(Qt::UserRole, fullFilePathData);
newItem->setText(itemText);
listWidget->insertItem(row, newItem);

and:

QListWidgeItem* currentItem = listWidget->currentItem();
if (currentItem != 0) {
     QVariant data = currentItem->data(Qt::UserRole);
     QString fullFilePath = data.toString();
}
Spathose answered 21/8, 2011 at 7:9 Comment(0)
L
13

Here is how it looks like in Python (PyQt5):

from PyQt5 import QtCore, QtWidgets


# Creates a QListWidgetItem
item_to_add = QtWidgets.QListWidgetItem()

# Setting your QListWidgetItem Text          
item_to_add.setText('String to Display')   
  
# Setting your QListWidgetItem Data  
item_to_add.setData(QtCore.Qt.UserRole, YOUR_DATA) 

# Add the new rule to the QListWidget
YOUR_QListWidget.addItem(item_to_add)            

Retrieving the data:

# Looping through items
for item_index in range(YOUR_QListWidget.count()):  

    # Getting the data embedded in each item from the listWidget
    item_data = YOUR_QListWidget.item(item_index).data(QtCore.Qt.UserRole)  

    # Getting the datatext of each item from the listWidget
    item_text = YOUR_QListWidget.item(item_index).text()  
Liquidator answered 22/6, 2020 at 12:41 Comment(1)
Thank you :) General problem is when you setdata to item without QtCore.Qt.UserRole, it changes text too.Potbelly

© 2022 - 2024 — McMap. All rights reserved.