Search code examples
c++qtqlistwidget

Getting full path from QListWidget


I have 2 listwidgets, lets call them listwidgetinput and listwidgetoutput. I have alot of files(only file name) on listwidgetinput. And i trim the file name before adding it to listwidgetinput like this it.fileName(). and i transfer the selected files to listdigetoutput like:

QList <QListWidgetItem*> items=ui->listWidgetinput->selectedItems();
for(int j=0;j<items.count();j++)
{
list= items.at(j)->text();
ui->listWidgetOutput->insertItem(j,list);

After i transfer the file can i get the path for all the files?. If Yes, how?

edit: code where whole path is available.

QString Dir, Type;
QStringList Files;
Qlistwidget wid

if (index==0)
  {
    Dir.append(C:\desktop....);
    type.append(".txt")
    wid = ui->listwidgetinput_txt;
    }
if (index ==1)
  {
    Dir.append(C:\desktop....);
    type.append(".doc")
    wid = ui->listwidgetinput_doc
    }
QDirIterator it(Dir, QStringList() << Type, QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext())
    {
        it.next();
        
        Files.append(it.fileName());
      }
wid->additems(Files);


Solution

  • Use QListWidgetItem::setData() to pass additional "invisible" properties like the full path when creating the item:

    auto item = new QListWidgetItem;
    item->setText(fileInfo.fileName());
    item->setData(Qt::UserRole, fileInfo.absoluteFilePath());
    ...
    

    Later you can retrieve it via QListWidgetItem::data():

    const auto fullPath = item->data(Qt::UserRole).toString();