How do you bind a QStringList to a QListView?
-
I have a collection of records, each containing two fields: a Name and a collection of strings associated with that name. I would like to bind the Name to a Label (no problems doing this) and the string collection to a QListView, such that the collection of strings displayed in the QListView update when a new record becomes active.
I tried doing this using two mechanisms but neither worked:
@
// Create the collection of records
QList<QStringList> itemsPerName;
QStringList tempList;
tempList << "A_Item1" << "A_Item2" << "A_Item3";
itemsPerName.append(tempList);
tempList.clear();
tempList << "B_Item1" << "B_Item2";
itemsPerName.append(tempList);
tempList.clear();
tempList << "C_Item1" << "C_Item2" << "C_Item3" << "C_Item4" << "C_Item5";
itemsPerName.append(tempList);
tempList.clear();// Initialize model int numRows = itemsPerName.count(); int numColumns = 3; QStandardItemModel *model = new QStandardItemModel(numRows, numColumns, this); // Convert each QStringList into a multi-row QStandardItem and load those into the Model const int itemsPerNameColumn = 0; for(int row = 0; row < numRows; row++) { QStandardItem *field = new QStandardItem(); QString thisItem; foreach(thisItem, itemsPerName[row]) { field->appendRow(new QStandardItem(thisItem)); } model->setItem(row, itemsPerNameColumn, field); }
@
Try #1: Use a QDataWidgetMapper the to bind the string collection to the QListView
@
QDataWidgetMapper *mapper = new QDataWidgetMapper(this);
mapper->addMapping(ui->qListView, itemsPerNameColumn);
@Try #2: Set the model directly on the QListView
@
ui->qListView->setModel(model);
ui->qListView->setModelColumn(itemsPerNameColumn);
@Does anyone know what I'm doing wrong, or if this is even possible?
-
There would certainly be a way to implement that using QStandardItem model. However, I think it would be easier, to use a custom model. See the "Model/View Introduction":http://doc.qt.nokia.com/latest/modelview.html .
-
[quote]I have a collection of records, each containing two fields: a Name and a collection of strings associated with that name. I would like to bind the Name to a Label (no problems doing this) and the string collection to a QListView, such that the collection of strings displayed in the QListView update when a new record becomes active.[/quote]
Can you elaborate more on the part "when a new record becomes active"? What do you mean? Do you have a QDWM-like interface, in which you move upon the records?
(Btw, Qt provides QStringListModel.)