Important: Please read the Qt Code of Conduct -

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)

    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:


  • @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
    //remove the items already in the widget
    int numItems = listWidget->count();
    for(int i = 0; i < numItems; ++i)
    //now that the list is "clean" all there is left to do is add the new items