Search code examples
c++qtqt5hidden-fieldqlistwidgetitem

Is it possible to add a hidden value to every item of qlistWidget


Is it possible to add hidden value to every item of qlistWidget.
I get data from the database and add it to qlistWidget.

I want to assign the id of every row as hidden data to every item in qlistWidget to use it in the future, like the HTML tag <input type="hidden" name="id" value="15" />.

The following is the code that get the data from database.

QSqlQuery qry;
qry.prepare("SELECT * FROM users");
qry.exec();
while(qry.next()){
     ui->listWidget->addItem(qry.value("username").toString());
}

Is it possible to do that ?


Solution

  • Use setData() and data(). Example:

    // set data
    auto *item = new QListWidgetItem(qry.value("username").toString());
    QVariant v;
    v.setValue(qry.value("id").toInt());
    item->setData(Qt::UserRole, v);
    ui->listWidget->addItem(item);
    
    // get back the data
    QVariant v = item->data(Qt::UserRole);
    int id = v.value<int>();