Suddenly getting crash when setting background color of QTableWidget

  • Hello, I am setting up a QTableWidget in the constructor of my main window as follows:
    @ ui->tableWidget->setRowCount(5);
    //QStringList *labels = new QStringList();
    QStringList labels;
    labels.append("Intake Pressure");
    labels.append("Intake Temperature");
    labels.append("Motor Temperature");
    labels.append("X Vibration");
    labels.append("Y Vibration");

    I get a crash below when I try to set the background color of some of the cells. This was working, then I was making changes unrelated to this widget, and it suddenly started crashing. I first noticed it crashing when I replaced the 0's in the second column with a variable. Then when I change them all back to 0, it still crashes.
    @//Set color of the cells to red
    QColor color( 240,0,0 );
    ui->tableWidget->item( 0, 0 )->setBackgroundColor( color ); //Crashing here
    ui->tableWidget->item( 1, 0 )->setBackgroundColor( color );
    ui->tableWidget->item( 2, 0 )->setBackgroundColor( color );
    ui->tableWidget->item( 3, 0 )->setBackgroundColor( color );
    ui->tableWidget->item( 4, 0 )->setBackgroundColor( color );@

    At the crash, the cursor is on the following line in qtablewidget.h:
    @ inline QColor backgroundColor() const
    { return qvariant_cast<QColor>(data(Qt::BackgroundColorRole)); }
    inline void setBackgroundColor(const QColor &color)
    { setData(Qt::BackgroundColorRole, color); } //Cursor is here@

    The crash window has a title bar "Signal received" and the content is "The inferior stopped because it received a signal from the Operating System. Signal name: SIGSEGV, Signal meaning: Segmentation fault" Any ideas what is going on?

    Thanks a lot,

  • Lifetime Qt Champion


    You are not creating any item for your table widget so you are accessing a null pointer.

    You first need to populate your QTableWidget with QTableWidgetItems

  • You are right of course. What is different now is that no items get put in the table before I try to set the color. What I need to do is detect whether there are items there before I set the color.
    What I did was fill the table with '-' items as soon as the table is created.
    Thanks for the help.

  • Lifetime Qt Champion

    You can also set items with empty text if you don't want anything in the cells

Log in to reply

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