1

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 ?

4

2 回答 2

2

使用 setData() 和 data()。例子:

// 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>();
于 2014-08-23T12:13:43.757 回答
1

创建您自己的继承自 QListWidgetItem 的类,您要隐藏的数据将成为您的类的成员。

于 2014-08-22T18:52:43.767 回答