QTableWidget::itemAt() returns seemingly random items
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(开发者_如何学C)));
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?
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());
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.
精彩评论