[solved] Trouble getting color from QTableWidgetItem

  • Hello, I am trying to do things like change the background color of a QTableWidgetItem when I click on it.

    @ QTableWidgetItem *cell = ui->tableWidget->itemAt( index.column(), index.row() );
    QColor color = cell->background().color(); //test code
    int r=40; int g=60; int b=80; int a=0;
    color.getRgb( &r, &g, &b, &a ); //OR
    r=color.red(); g=color.green(); b=color.blue();
    qDebug() << "r=" << r << " g=" << g << " b=" << b;@

    Both getRgb and color.red() etc. are returning 0,0,0. Some of the cells are gray, some of them are white. Why am I not getting the correct color?

  • Apparently I am not getting the cell correctly because cell->setText("abc") does not work.

  • I figured it out. QTableWidgetItem::itemAt "returns the item at the position equivalent to QPoint(ax, ay) in the table widget's coordinate system" not column and row in the table. I changed itemAt() to item() and reversed row/column. Here is what works:

    @QTableWidgetItem *cell = ui->tableWidget->item( index.row(), index.column() );
    QColor color = cell->background().color();
    int r=0; int g=0; int b=0; int a=0;
    color.getRgb( &r, &g, &b, &a );
    qDebug() << "r=" << r << " g=" << g << " b=" << b;
    qDebug() << "checked=" << cell->checkState(); //I made some of the cells Qt::ItemIsUserCheckable@

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.