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

后端 未结 2 1971
渐次进展
渐次进展 2021-02-13 01:44

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 t

2条回答
  •  一整个雨季
    2021-02-13 01:56

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

提交回复
热议问题