Finding index of a cell containing a value and hig

2019-02-26 23:39发布

问题:

How can we find out the index (i.e both row and column numbers) of a cell containing a QString in a QTableView using QT c++?

(P.S.:Without clicking on the cell in qtableview)

回答1:

You can use findItems() function to find your cell.

findItems() function returns a list of items that match the given text, using the given flags, in the given column.

for (int index = 0; index < model->columnCount(); index++)
{
    QList<QStandardItem*> foundLst = model->findItems("YourText", Qt::MatchExactly, index);
}

If you want to get index of found item and highlight it use this code:

for (int index = 0; index < model->columnCount(); index++)
{
    QList<QStandardItem*> foundLst = model->findItems("YourText", Qt::MatchExactly, index); 
    int count = foundLst.count();
    if(count>0)
    {
            for(int k=0; k<count; k++)
            {
                 QModelIndex modelIndex = model->indexFromItem(foundLst[k]);
                 qDebug()<< "column= " << index << "row=" << modelIndex.row();
                ((QStandardItemModel*)modelIndex.model())->item(modelIndex.row(),index)->setData(QBrush(Qt::green),Qt::BackgroundRole);
            }
    }
}

More info:

QTableView: The QTableView class provides a default model/view implementation of a table view.

QStandardItemModel: The QStandardItemModel class provides a generic model for storing custom data.