C++ 如何在qtablewidget中获取字符串的行号

C++ 如何在qtablewidget中获取字符串的行号,c++,qt,C++,Qt,我正在使用Qt5.4.0并创建了一个QTableWidget。该表有多个行和列 在我的应用程序中,我想在该表中搜索一个字符串,如果该字符串存在,我想知道行号 我在Qt5.4.0文档中找不到任何这样的api 是否有人有这样的api或类似的我正在寻找的理解 提前谢谢 您可以使用: QString searchtext=“text”; QList items=ui->tableWidget->findItems(searchtext,Qt::matchjustice); 对于(int i=0;irow

我正在使用Qt5.4.0并创建了一个QTableWidget。该表有多个行和列

在我的应用程序中,我想在该表中搜索一个字符串,如果该字符串存在,我想知道行号

我在Qt5.4.0文档中找不到任何这样的api

是否有人有这样的api或类似的我正在寻找的理解

提前谢谢

您可以使用:

QString searchtext=“text”;
QList items=ui->tableWidget->findItems(searchtext,Qt::matchjustice);
对于(int i=0;irow();
//...
}
请注意,您可以将一个额外的参数传递给
findItems
,以设置一个或多个参数。

您可以使用模型的方法:

for (int col=0; col<tableWidget->columnCount(); col++){
    // return a list of all matching results
    QModelIndexList results = tableWidget->model()->match(
        tableWidget->model()->index(0, col),
        Qt::DisplayRole,
        "yourstring",
        -1,
        Qt::MatchContains
    );
    // for each result, print the line number
    for (QModelIndex idx : results)
        qDebug() << idx.row();
}
for(int col=0;colcolcolumncount();col++){
//返回所有匹配结果的列表
QModelIndexList results=tableWidget->model()->匹配(
tableWidget->model()->索引(0,列),
Qt::DisplayRole,
“你的字符串”,
-1,
Qt::MatchContains
);
//对于每个结果,打印行号
对于(QModelIndex idx:results)

qDebug()您不需要迭代列并多次调用
match()
函数。仅为模型索引(0,0)调用
tableWidget->model()->match()
函数一次就足够了。@vahancho,在文档中,它写着“返回开始索引列中项目的索引列表”是的,但是您可以使用
Qt::MatchRecursive
标志从左上角单元格(行=0,列=0)开始搜索整个表。@vahancho,使用
Qt::MatchContains | Qt::MatchRecursive
对我不起作用
for (int col=0; col<tableWidget->columnCount(); col++){
    // return a list of all matching results
    QModelIndexList results = tableWidget->model()->match(
        tableWidget->model()->index(0, col),
        Qt::DisplayRole,
        "yourstring",
        -1,
        Qt::MatchContains
    );
    // for each result, print the line number
    for (QModelIndex idx : results)
        qDebug() << idx.row();
}