Search code examples
c++qtqtableview

Qt C++ Get data from every cell of a selected row from a QTableView


Is there any way to get data from a selected row from a table view? i've used QModelIndexList ids = ui->tableView->selectionModel()->selectedRows(); which returns a list of the indexes of the selected rows. I don't need the index. I need the data from every cell of the selected row.


Solution

  • QVariant data(const QModelIndex& index, int role) const
    

    is being used for returning data. If you need to get data you are doing it here based on QModelIndex row and column and retrieving it from some container, maybe

    std::vector<std::vector<MyData> > data;
    

    You have to define such mapping and use it in data() and setData() functions to handle interaction with underlying model data.

    Alternatively QAbstractItemModel and QTreeView offers the way to assign your class i.e. TreeItem to each QModelIndex, so you can next retrieve a pointer to each data using static_cast of pointer returned from QModelIndex.internalPointer() function:

    TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
    

    so then you can create some mapping:

    // sets the role data for the item at <index> to <value> and updates 
    // affected TreeItems and ModuleInfo. returns true if successful
    // otherwise returns false
    bool ModuleEnablerDialogTreeModel::setData(const QModelIndex & index,
        const QVariant & value, int role) {
      if (role
          == Qt::CheckStateRole&& index.column()==ModuleEnablerDialog_CheckBoxColumn) {
        TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
        Qt::CheckState checkedState;
        if (value == Qt::Checked) {
          checkedState = Qt::Checked;
        } else if (value == Qt::Unchecked) {
          checkedState = Qt::Unchecked;
        } else {
          checkedState = Qt::PartiallyChecked;
        }
        //set this item currentlyEnabled and check state
        if (item->hierarchy() == 1) { // the last level in the tree hierarchy
          item->mModuleInfo.currentlyEnabled = (
              checkedState == Qt::Checked ? true : false);
          item->setData(ModuleEnablerDialog_CheckBoxColumn, checkedState);
          if (mRoot_Systems != NULL) {
            updateModelItems(item);
          }
        } else { // every level other than last level
          if (checkedState == Qt::Checked || checkedState == Qt::Unchecked) {
            item->setData(index.column(), checkedState);
            // update children
            item->updateChildren(checkedState);
            // and parents
            updateParents(item);
    

    example of implementation