【问题标题】:Qt/C++: Getting the data at a certain cell in a QTableViewQt/C++:获取 QTableView 中某个单元格的数据
【发布时间】:2011-05-13 07:46:52
【问题描述】:

我试图在QTableView 的某个单元格中获取文本。例如:

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

这应该会在我的QTableView 中的第 0 列第 2 行的单元格中获取文本。问题是,这不是它在做什么!无论我在indexAt() 中传递给QPoint() 的参数是什么,我都会在单元格0,0 处获得文本。我不知道这是为什么……有什么帮助吗?谢谢!

[编辑]
我也试过这个:

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

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

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

它应该在单元格 2,2 处获得 QModelIndex 并输出其行和列,当然应该是 2 和 2。但是,我得到了 0 和 0!所以看起来这可能是QTableView::indexAt() 的问题,无论是我的使用还是某种错误。有人能解释一下吗?

【问题讨论】:

  • indexAt(QPoint(0,2) 将返回小部件位置 X=0 Y=2 处的单元格的 QModelIndex,而不是 Row/Col 0,2

标签: c++ qt qtableview


【解决方案1】:

解决方法:

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

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

【讨论】:

  • 我认为这是因为 QPoint 用于根据光标的某个位置获取值。我正在使用 QPoint 基于右键单击获取单元格值。
  • indexAt() 返回视图中某个像素位置的索引。 (0,2) 距离上边框仅两个像素,因此对应于 index(0,0)。顺便说一句,ui->tblInventory->model()->index(0,2).data().toString() 也可以。
【解决方案2】:

这个也可以,而且更短:

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

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

(model used top 是绑定到这个tblInventory的QAbstractModel)

【讨论】:

  • 这不是更短或更长的问题。在这里,您创建额外的实例,使他的解决方案更好。反正干得好
【解决方案3】:

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

【讨论】:

  • 你能再解释一下吗?我正在使用 QSqlQueryModel。我也尝试过: QString codestring = "" + ui->tblInventory->model()->data(ui->tblInventory->indexAt(QPoint(0,2))).toString() + " ";但这也不起作用。
【解决方案4】:

试试这个:

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() + "*";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多