Important: Please read the Qt Code of Conduct -

QListWidgetItem storing a multi value field

  • I have a QListWidget that I add QListWidgetItem(s) to and remove from. The problem I'm trying to find a solution to is each QListWidgetItem adds a QString to the QListWidget. I still want it to do that but also add and ID associated with each QString in the background. So that if I want to delete any QString from the QListWidget, its associated ID is deleted as well.

    I thought about adding std::map, storing ID and string in it before adding the QString to the QListWidget but if I add similar QString, how would I know which QString is associate with which ID to remove?

    Is there an easier solution?

  • Lifetime Qt Champion

    Something like this ?
    You could store an ID for your map.

    Its a QVariant so you can also use your own type/class/struct if you register it,
    Q_DECLARE_METATYPE(CustomType) part.

  • I modified the code in the link you provided. The code is working fine but occasionally I'm getting segmentation fault and the app terminates. Here is my code:

            QListWidgetItem* lineItem = new QListWidgetItem(name, ui->listWidget);
            lineItem->setData(Qt::UserRole, ID);
            lineItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable );

    Will using a parent ( ui->listWidget) in the QListWidgetItem cause problems?

    to retrieve ID, I use the following code:

        for(int i = 0; i < ui->listWidget->count(); ++i)
            QListWidgetItem* currentItem = ui->listWidget->item(i); 
            if (currentItem != 0) {
                 QVariant id = currentItem->data(Qt::UserRole);

    The code compiles and run but will it cause program failure?

  • Lifetime Qt Champion


    What does a run through the debugger tell you about that crash ?

Log in to reply