How do I get text from an item in a qtablewidget?

14,773

It looks like you're using QTableWidget::itemAt when you should be using QTableWidget::item.

Simply put, itemAt finds the QTableWidgetItem at the pixel coordinates (ax, ay), while item returns the QTableWidgetItem at the specified row and column. The text is always "test" because you are always asking the table for the widget very close to (0, 0), which is in the top-left corner.

Share:
14,773
Tim Hutchison
Author by

Tim Hutchison

I'm a Senior Software Engineer at Cohen & Company in Cleveland, OH. We build internal applications using Typescript, Vuejs, Nodejs, and Expressjs that improve the efficiency and operations of the company. In my free time I enjoy playing various sports (primarily golf and ping pong), watching football and hockey, mentoring high schoolers, reading, and spending time with friends.

Updated on June 14, 2022

Comments

  • Tim Hutchison
    Tim Hutchison almost 2 years

    I want to highlight all of the cells in my table that have the same value in the first column, but have a different value in any other cell. So, for example, if I have two records in my table:

    test, 25, 15, 45
    test, 25, 5, 45    
    

    I would want to highlight the values 15 and 5.

    I have tried the following code, but the text I get from the item calls is always "test" regardless of what item I am accessing.

    // Highlight differences in the data
    for( int row=0; row < ui->table_Data->rowCount(); row++ )
    {
        qDebug() << "going through rows";
        for( int remaining_rows=row+1; remaining_rows < ui->table_Data->rowCount(); remaining_rows++)
        {
            qDebug() << "going through remaining rows";
            for( int column=0; column<ui->table_Data->columnCount(); column++ )
            {
                qDebug() << "going through columns";
                qDebug() << row << ":" << remaining_rows << column;
                qDebug() << ui->table_Data->itemAt(row,column)->text();
                qDebug() << ui->table_Data->itemAt(remaining_rows,column)->text();
                if( ui->table_Data->itemAt(row,column)->text().compare(ui->table_Data->itemAt(remaining_rows,column)->text()) != 0)
                {
                     qDebug() << "data does not match";
                     ui->table_Data->item(row,column)->setBackground(Qt::yellow);
                     ui->table_Data->item(remaining_rows,column)->setBackground(Qt::yellow);
                }
            }
        }
    }
    
  • Tim Hutchison
    Tim Hutchison almost 10 years
    Thank you MrMallIronmaker! I was always confused on the difference between item() and itemAt() and now I understand.