Solved How to setData with QJsonObject to QListWidgetItem ?
-
I have a QListWidget, I am populating the list with data from a QJsonArray where each element of the array is a QJsonObect. I am trying to use the QListWidgetItem setData method to add the JSON data:
QListWidgetItem* pobjItem = item(intRow); if ( pobjItem == nullptr ) { pobjItem = new QListWidgetItem(this); } if ( pobjItem != nullptr ) { pobjItem->setData(Qt::UserRole, objRef); QVariant varTemp = pobjItem->data(Qt::UserRole); if ( varTemp.isValid() == true ) { QJsonDocument objDoc(QJsonDocument::fromJson(varTemp.toByteArray())); QJsonValue objVerified(objDoc.object()); qdbg() << "HACK!"; } pobjItem->setText(citrFound->toString()); }
Using Qt Creator I can see that objRef is populated and contains a valid JSON object, the code that follows the setData call is just to verify that the data is stored correct, however although varTemp.isValid returns true the byte array is empty and objVerified does not contain the data that was set.
How can I fix this to store a JSON object with each item?
-
@jsulm , just solved this:
QListWidgetItem* pobjItem = item(intRow); if ( pobjItem == nullptr ) { pobjItem = new QListWidgetItem(this); } if ( pobjItem != nullptr ) { QVariant varTemp(objRef), varVerify; pobjItem->setData(Qt::UserRole, varTemp); varVerify = pobjItem->data(Qt::UserRole); if ( varVerify.isValid() == true ) { QJsonValue objVerified(varVerify.toJsonValue()); qdbg() << "HACK!"; } pobjItem->setText(citrFound->toString()); }
-
@SPlatten said in How to setData with QJsonObject to QListWidgetItem ?:
varTemp.toByteArray()
What does this return?
-
@SPlatten
setData()
returns abool
for success/failure, which you should always check in code. -
@jsulm , just solved this:
QListWidgetItem* pobjItem = item(intRow); if ( pobjItem == nullptr ) { pobjItem = new QListWidgetItem(this); } if ( pobjItem != nullptr ) { QVariant varTemp(objRef), varVerify; pobjItem->setData(Qt::UserRole, varTemp); varVerify = pobjItem->data(Qt::UserRole); if ( varVerify.isValid() == true ) { QJsonValue objVerified(varVerify.toJsonValue()); qdbg() << "HACK!"; } pobjItem->setText(citrFound->toString()); }