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

冷暖自知 提交于 2019-12-09 15:05:00

问题


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.


回答1:


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();
}


来源:https://stackoverflow.com/questions/7136818/can-i-store-some-user-data-in-every-item-of-a-qlistwidget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!