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

随声附和 提交于 2019-12-02 04:47:05

问题


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.



来源:https://stackoverflow.com/questions/45543721/finding-index-of-a-cell-containing-a-value-and-highlighting-all-those-cells-in-q

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!