Coloring QStandardItem doesn't work

  • Hello,

    I am trying to let the user color a cell in a QTableView. This is my code so far:

    void customTable::changeColor()
        QItemSelectionModel *sModel = ui->tableView->selectionModel();
        QModelIndexList selectedLists;
        selectedLists = sModel->selectedIndexes();
        QColor changeColor = pickColor();
        tableModel->item(0,0)->setData(QVariant(QBrush(changeColor)), Qt::BackgroundRole); //This works
        tableModel->item(1,1)->setData(QVariant(QBrush(changeColor)), Qt::BackgroundRole); //This will crash the program
        /*for(int i = 0; i < selectedLists.size(); ++i)
            QModelIndex index =;
            qDebug() << index.row() << " " << index.column();
            //tableModel->item(index.row(), index.column())->setData(QVariant(QBrush(changeColor)), Qt::BackgroundRole);

    However, even if there are way more than one column and one row, the program will execute the first call but not the second one. Does anyone know what the problem might be (ignore the other pieces of the code, those are for later)?

  • Lifetime Qt Champion


    Did you check whether you had a valid item before calling setData on it ?

  • @SGaist Both rowCount and columnCount are higher than one so yes, I presume that the indexes are valid.

  • Lifetime Qt Champion

    My suggestion stands. You may not have an item there hence your crash. You should check its validity.

  • @SGaist And how exactly can I check whether I have an item at a certain position?

    EDIT: Nevermind, I got what you meant and managed to fix it. Thank you!

  • Lifetime Qt Champion

    The model->item(row,col) will return NULL if no item is inserted there.
    I would use a function to check and set color.
    alt text

    void MainWindow::setItemColor(QStandardItem* item, QColor color) {
      if (!item) {
          qDebug() << "item NULL"; return;
      item->setData(QVariant(QBrush(color)), Qt::BackgroundRole);
    MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
      QStandardItemModel* model = new QStandardItemModel(2, 3, this); //2 Rows and 3 Columns
      model->setHorizontalHeaderItem(0, new QStandardItem(QString("Column1 Header")));
      model->setHorizontalHeaderItem(1, new QStandardItem(QString("Column2 Header")));
      model->setHorizontalHeaderItem(2, new QStandardItem(QString("Column3 Header")));
       // insert one item
      QStandardItem* firstRow = new QStandardItem(QString("ColumnValue"));
      model->setItem(0, 0, firstRow);  
      setItemColor(firstRow, Qt::red); // color it

  • @mrjj Yep. I hadn't realised that I had to insert a QStandardItem in every cell. Thanks for your help!

  • Lifetime Qt Champion

    Ah, yes. well that is a classic as the cells look normal and can be selected but
    its all NULL items.

Log in to reply