Coloring QStandardItem doesn't work
Solved
General and Desktop
-
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; if(!sModel->hasSelection()) return; 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 = selectedLists.at(i); 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)?
-
Hi,
Did you check whether you had a valid item before calling setData on it ?
-
My suggestion stands. You may not have an item there hence your crash. You should check its validity.
-
Hi
The model->item(row,col) will return NULL if no item is inserted there.
I would use a function to check and set color.
Like
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) { ui->setupUi(this); 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 ui->tableView->setModel(model); }
-
@El3ctroGh0st
Ah, yes. well that is a classic as the cells look normal and can be selected but
its all NULL items.