Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Getting Information back out of QListWidgetItem that has a QMap in it



  • Hi im trying to figure out how I can get Information out of a QListWidgetItem.
    I have program that has a QMap

    QMap<int,std::tuple<QString,QString,QString>>map; 
     map.insert(5,std::make_tuple("A","b","c"));
    

    I insert this map into a QListWidget like this

        QMapIterator<int,std::tuple<QString,QString,QString>> i(map);
        QString name;
        int id;
        while(i.hasNext()){
            i.next();
            name = std::get<0>(i.value());
            id = i.key();
            //qDebug () << i.key() << " " << std::get<0>(i.value());
            QListWidgetItem *item = new QListWidgetItem(name);
            item->setData(Qt::UserRole, id);
            ui->uebungs_liste->addItem(item);
        }
    

    uebungs_liste is the QListWidget and item the QListWidgetItem

    Now I want to access the information of the QListWidgetItem when you click on it how do I i go about achieving this.



  • @resist95
    [signal]void QListWidget::itemClicked(QListWidgetItem *item) signal is emitted for you to slot into. The fact that you happen a store a map as data is neither here nor there to retrieval.



  • ok so once i insert it into the list the information is gone?



  • @resist95
    No, if you inserted it with item->setData(Qt::UserRole, id); you can retrieve it with int id = item->data(Qt::UserRole);.



  • @JonB
    im very new to Qt and the item->setData(Qt::UserRole,id) line was from a tutorial could you elaborate how I get the Information out of the item or point me towards a tutorial where I can look it up.



  • @resist95
    Well, I would have expected that tutorial surely to show you how you retrieve the data set via setData()?

    What can I say, given that I've given already typed in the statement you need?

    connect(myListWidget, &QListWidget::itemClicked, this, &MainWindow::onListWidgetItemClicked);
    ...
    void MainWindow::onListWidgetItemClicked(QListWidgetItem *item)
    {
        # next line retrieves `id` set from previous `item->setData(Qt::UserRole, id);`
        QVariant v = item->data(Qt::UserRole);
        bool ok;
        int id = v.toInt(&ok);
        if (ok)
            qDebug() << id;
    }
    


  • @JonB
    It sadly didnt also your code returns no viable conversion int to qvariant it should be

    QVariant id = item->data(Qt::UserRole)
    

    but anyway thank you ill try to figure out the rest myself



  • @resist95
    Yes, you can use [I have corrected my answer]:

    QVariant v = item->data(Qt::UserRole);
    bool ok;
    int id = v.toInt(&ok);
    if (ok) ...
    

    or whatever is necessary for your exact situation.


Log in to reply