QListWidget remove duplicates



  • Hello.
    I am new to QT and I'm not sure how to get rid of duplicates in a QListWidget.

    I have the following code:

    for (i=0;i<fileNames.length();i++)
    if (fileNames[i] != temp)
    {
        ui->listWidget->addItem(fileNames[i]);
    }
    

    fileNames is a QStringList from QFileDialog. The temp variable is a QString that stores a QUrl.ToString() as a hack to something.

    My question is how can I prevent duplicates from happening in the QListWidget? I tried looping through it, unsuccessfully. It's probably me being an idiot. :D


  • Moderators

    Hi, welcome to devnet.

    A simple preprocessing of the list should do:

    fileNames.removeDuplicates();
    fileNames.removeOne(temp);
    ui->listWidget->addItems(fileNames);
    


  • @Chris-Kawa I'm not actually sure how to do the first part. The trouble is that the program allows the user to select files to copy, and the user can select them more than once using the dialog.

    This means that there might be the occasion where listWidget already has the entry and the user is trying to add it again by accident. I need to compare both fileNames and listWidget and check if they have any duplicates.


  • Moderators

    Then it's just a matter of removing from the list items that are already added. Something like this:

    //get the list from somewhere
    QStringList fileNames = ...
    
    //remove the temp item you mentioned
    fileNames.removeOne(temp);
    
    //remove the items already in the widget
    int numItems = listWidget->count();
    for(int i = 0; i < numItems; ++i)
        fileNames.removeOne(listWidget->item(i)->text());
    
    //now that the list is "clean" all there is left to do is add the new items
    listWidget->addItems(fileNames);
    


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