Getting full path from QListWidget



  • 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 :

    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())
        {
            auto item = new QListWidgetItem;
            it.next();
            item->setText(it.fileName());
            item->setData(Qt::UserRole, it.filePath())
             myWidget->addItem(item);
          }
    wid->additems(Files);
    

    i want to retireve the file path of all items in listwidgetoutput. I insert items to listwidgetoutput like this:

    QList <QListWidgetItem*> items=ui->listWidgetinput->selectedItems();
    for(int j=0;j<items.count();j++)
    {
    list= items.at(j)->text();
    ui->listWidgetOutput->insertItem(j,list);``
    
    How do i retrieve the path of the files in listwidgetoutput

  • Moderators

    Since you store the path in the Qt::UserRole you can get it back from there too i.e.

    for(auto item: items)
    {
        auto filename = item->text(); // this is shortcut for: item->data(Qt::DisplayRole).toString()
        auto path     = item->data(Qt::UserRole).toString();
        ...
    }
    


  • Qt::userRole holds path of all files in listwidgetinput, only selected files are transfered to listwidgetoutput. I was confused on how to get path of only selected files.



  • One thing which I saw while adding elements to output list, you are lonely adding the text. That means you are NOT adding the item from input list but just text from each item. This may be giving problem for you. Instead of inserting the text() insert the complete item from inputList to output list. After this you can iterate through items from ListwidgetOutput and fetch user role data as well.


  • Moderators

    So do you want all paths or only the selected in input ones?
    For selected you would do:

    auto items = ui->listWidgetinput->selectedItems();
    for(auto item : items)
    {
        auto path = item->data(Qt::UserRole).toString();
        ui->listWidgetOutput->addItem(path);
    }
    

    For all you would do:

    auto numItems  = ui->listWidgetinput->count();
    for(int i = 0; i < numItems; ++i)
    {
        auto path = ui->listWidgetinput->item(i)->data(Qt::UserRole).toString();
        ui->listWidgetOutput->addItem(path);
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.