21

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

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!

[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:

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

It should get the QModelIndex at 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?

rc0r
  • 18,631
  • 1
  • 16
  • 20
Joseph
  • 12,678
  • 19
  • 76
  • 115

4 Answers4

31

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.

Joseph
  • 12,678
  • 19
  • 76
  • 115
  • 1
    I think it's because QPoint is used to get a value based on certain position of the cursor. I'm using QPoint to get the cell value based on a right click. – Amree Nov 21 '10 at 08:35
  • 3
    indexAt() returns the index at a certain *pixel position* in the view. (0,2) is just two pixels from the top border, and thus corresponds to index(0,0). Btw, ui->tblInventory->model()->index(0,2).data().toString() also works. – Frank Osterfeld Nov 21 '10 at 09:33
10

This one work too and it's shorter:

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

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

(model used top is the QAbstractModel that is bound to this tblInventory)

Mahir Zukic
  • 432
  • 7
  • 13
  • it is not about shorter or longer. Here you create extra instances that's make his solution better. Good job anyway – AAEM Apr 23 '18 at 02:05
0

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.

dpq
  • 9,028
  • 10
  • 49
  • 69
  • Can you explain a bit more? I'm using QSqlQueryModel. I've also attempted: QString codestring = "*" + ui->tblInventory->model()->data(ui->tblInventory->indexAt(QPoint(0,2))).toString() + "*"; but this doesn't work either. – Joseph Nov 21 '10 at 08:12
0

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() + "*";
SIFE
  • 5,567
  • 7
  • 32
  • 46