Qt/C++:获取 QTableView 中某个单元格的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4236942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:54:49  来源:igfitidea点击:

Qt/C++: Getting the data at a certain cell in a QTableView

c++qtqtableview

提问by Joseph

I'm trying to get the text at a certain cell in a QTableView. For example:

我正在尝试获取QTableView. 例如:

QString codestring = "*" + ui->tblInventory->indexAt(QPoint(0,2)).data().toString() + "*";

This should get the text at the cell in column 0 row 2 in my QTableView. The problem is, that's not what it's doing!. Regardless of the arguments I pass into the QPoint()in the indexAt(), I get the text at cell 0,0. I have no idea why this is... any help? Thanks!

这应该在我的QTableView. 问题是,这不是它在做什么!不管我传递到参数QPoint()indexAt(),我会在小区0,0中的文本。我不知道这是为什么……有什么帮助吗?谢谢!

[edit]
I've also tried this:

[编辑]
我也试过这个:

QString codestring = "*" + ui->tblInventory->model()->data(ui->tblInventory->indexAt(QPoint(0,2))).toString() + "*";

[Edit 2] Trying to find out what's going on, I put in this line of code:

[编辑 2] 试图找出发生了什么,我把这行代码:

qDebug()<< ui->tblInventory->indexAt(QPoint(2,2)).row() << " and " <<  ui->tblInventory->indexAt(QPoint(2,2)).column();

It should get the QModelIndexat cell 2,2 and output its row and its column, which of course should be 2 and 2. However, I get 0 and 0! So it seems like this might be a problem with QTableView::indexAt(), whether its my usage or some sort of bug. Can anyone shed some light?

它应该得到QModelIndex单元格 2,2 并输出它的行和列,当然应该是 2 和 2。但是,我得到 0 和 0!所以看起来这可能是 的问题QTableView::indexAt(),无论是我的用法还是某种错误。任何人都可以透露一些信息吗?

回答by Joseph

Resolved with:

解决了:

ui->tblInventory->model()->data(ui->tblInventory->model()->index(0,2)).toString()

Not quite sure why the above doesn't work, but this does. Thanks for the help.

不太确定为什么上述方法不起作用,但确实如此。谢谢您的帮助。

回答by Mahir Zukic

This one work too and it's shorter:

这个也有效,而且更短:

QModelIndex index = model->index(row, col, QModelIndex());

ui->tblInventory->model()->data(index).toString();

(modelused top is the QAbstractModel that is bound to this tblInventory)

model使用的 top 是绑定到这个的 QAbstractModel tblInventory

回答by dpq

Check the data()function provided by the model that your QTableView uses, the effect that you describe is probably observed due to a bug in it.

检查data()您的 QTableView 使用的模型提供的功能,您描述的效果可能是由于其中的错误而观察到的。

回答by SIFE

Try this:

尝试这个:

QModelIndex index = ui->tblInventory->indexAt(p); // p is a QPoint you get from some where, may be you catch right click
QString codestring = "*" + index->data().toString() + "*";