views:

59

answers:

2

I've just started using Qt, so please bear with me. When I use QTableWidget->getItemAt(), it returns a different item from if I used currentItemChanged and clicked the same item. I believe it's necessary to use itemAt() since I need to get the first column of whatever row was clicked.

Some example code is below:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QList<QString> rowContents;

    rowContents << "Foo" << "Bar" << "Baz" << "Qux" << "Quux" << "Corge" << "Grault" << "Garply" << "Waldo" << "Fred";

    for(int i =0; i < 10; ++i)
    {
        ui->tableTest->insertRow(i);
        ui->tableTest->setItem(i, 0, new QTableWidgetItem(rowContents[i]));
        ui->tableTest->setItem(i, 1, new QTableWidgetItem(QString::number(i)));
    }
}

//...

void MainWindow::on_tableTest_currentItemChanged(QTableWidgetItem* current, QTableWidgetItem* previous)
{
    ui->lblColumn->setText(QString::number(current->column()));
    ui->lblRow->setText(QString::number(current->row()));
    ui->lblCurrentItem->setText(current->text());
    ui->lblCurrentCell->setText(ui->tableTest->itemAt(current->row(), current->column())->text());
}

For the item at 1x9, lblCurrentItem displays "9" (as it should,) whereas lblCurrentCell displays "Quux". Am I doing something wrong?

+1  A: 

Looks like your table is getting sorted as per the 0th ("Foo, Bar, ...") column. That way 'Q'uux being at 9, before Waldo makes sense. Either insert the numbers at 0th column or disable sorting or I think you got the point. There are many solutions.

sambha
Jordon, Can you try using item(row, col) instead of itemAt. Also note that Qt APIs take (row, column) as arguments. You could be using it the other way - (column, row). HTH.
sambha
+3  A: 

Qt documenration says:

QTableWidgetItem * QTableWidget::itemAt ( int ax, int ay ) const

Returns the item at the position equivalent to QPoint(ax, ay) in the table widget's coordinate system, or returns 0 if the specified point is not covered by an item in the table widget.

See also item().

So you should probably use item(row, column) instead: ui->lblCurrentCell->setText(ui->tableTest->item(current->row(), current->column())->text());

itemAt() versus item()
You're right, looks like I used itemAt() when I should have been used item(). I should have read the documentation more thoroughly. Thanks for the help!
Jordan Milne