2013-09-28 68 views
7

是否有任何方法從表視圖中的選定行獲取數據?我用 QModelIndexList ids = ui->tableView->selectionModel()->selectedRows();它返回所選行的索引列表。我不需要索引。我需要來自所選行的每個單元格的數據。Qt C++從QTableView中獲取選定行的每個單元的數據

+0

使用'QModelIndex ::數據(INT角色)'讓SENCE? – vahancho

回答

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

正用於返回數據。如果你需要得到的數據,你在這裏做基於QModelIndex行和列和一些容器取出它,也許

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

你必須定義這樣的映射,並用它在data()setData()函數來處理與互動基礎模型數據。

或者QAbstractItemModelQTreeView提供給你的類即TreeItem分配給每個QModelIndex的方式,這樣你就可以在下一個檢索使用QModelIndex.internalPointer()函數返回指針static_cast的指針,每一個數據:

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); 

example of implementation

7

你可以試試這個

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()); 
1
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(); 
相關問題