Qt C++从QTableView获取所选行中每个单元格的数据

9

有没有办法从表格视图中选择的行中获取数据?我已经使用了QModelIndexList ids = ui->tableView->selectionModel()->selectedRows();,它返回所选行的索引列表。我不需要索引,我需要所选行中每个单元格的数据。


使用QModelIndex::data(int role)有意义吗? - vahancho
3个回答

9

你可以试一下这个

int rowidx = ui->tblView->selectionModel()->currentIndex().row();
ui->txt1->setText(model->index(rowidx , 0).data().toString());
ui->txt2->setText(model->index(rowidx , 1).data().toString());
ui->txt3->setText(model->index(rowidx , 2).data().toString());
ui->txt4->setText(model->index(rowidx , 3).data().toString());

2
Try this for getting data. selectedRows(0) indicates first column of selected rows, selectedRows(1) indicates second column of selected rows row likewise

QItemSelectionModel *select = ui->existingtable->selectionModel();
qDebug()<<select->selectedRows(0).value(0).data().toString();
qDebug()<<select->selectedRows(1).value(0).data().toString();
qDebug()<<select->selectedRows(2).value(0).data().toString();
qDebug()<<select->selectedRows(3).value(0).data().toString();

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

这里使用 QModelIndex 的行和列来获取数据,并从某个容器中检索数据。

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

您需要定义这样的映射,并在data()setData()函数中使用它来处理与底层模型数据的交互。
或者,您可以使用QAbstractItemModelQTreeView提供的方法将您的类(例如TreeItem)分配给每个QModelIndex,因此您可以使用static_castQModelIndex.internalPointer()函数返回的指针检索每个数据的指针。
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());

那么您可以创建一些映射:
// 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);

实现示例

该链接提供了一个关于Qt技术的实现示例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接