Trial and error led me to this. I have a QListView and a QStandardItemModel. I select one of the items in the View and would like to retrieve it for use.
Need to know which row index was clicked (be sure and set the QListView selectingBehavior to "selectRows," otherwise you may get just a single item within the row). That "selectionModel()" is a tricky bit that wasn't obvious from the docs.
QModelIndexList indices = ui->treeView->selectionModel()->selectedRows();
The QListView is setup so that only a single row can be selected at a time. Verfiy that at least one row was chosen, then determine the correct row index:
if ( indices.count() == 1 )
{
QModelIndex idx = indices[0];
int row = idx.row();
Retrieve the model from the view:
QStandardItemModel *model =
dynamic_cast < QStandardItemModel* >(ui->treeView->model());
QStandardItemModel allows you to retrieve a QStandardItem using integers for row and column (I got wrapped around the axle about QModelIndex from model->data(), but the createIndex() method was protected inside QStandardItemModel. We don't need that, just the integer indices)
QStandardItem *firstColumnItem = model->item(row, 0);
Internally, the object is stored as a QVariant. My two columns contain QString and QDateTime. FYI I used Qt::DisplayRole when inserting the objects into the model.
QVariant
firstColumnVariant(firstColumnItem->data(Qt::DisplayRole));
QString
firstColumnString(firstColumnVariant.toString());
Next, I got the second column with some shorthand:
QVariant
dateTimeVariant(model->item(row,1) ->data(Qt::DisplayRole));
QDateTime
dateTime(dateTimeVariant.toDateTime());
And popped it up in a MessageBox:
QMessageBox(QMessageBox::Information, firstColumnString, dateTime).exec();
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment