Finding index of a cell containing a value and highlighting all those cells in QTableView

前端 未结 1 936
旧时难觅i
旧时难觅i 2021-01-22 03:44

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 qtable

相关标签:
1条回答
  • 2021-01-22 04:14

    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.

    0 讨论(0)
提交回复
热议问题