Add items to columns in QStandardItemModel

James Franco picture James Franco · Mar 17, 2016 · Viewed 9.8k times · Source

I am currently adding rows to my QTableView as such

QStandardItem* itm;
QStandardItemModel* model = new QStandardItemModel(this);
model->setColumnCount(2);
model->appendRow(new QStandardItem("Some Text in Column1");

How do I add items to column 2 dynamically by appending? In the above example column 2 is empty. How do I add item to column 2?

Answer

PowerGlove picture PowerGlove · Mar 17, 2016

Calling appendRow(QStandardItem *) only adds a single item to the first column. You would need to pass in a QList to appendRow() to add items to each column, e.g.:

QList<QStandardItem *> items;

items.append(new QStandardItem("Column 1 Text"));
items.append(new QStandardItem("Column 2 Text"));

QStandardItemModel* model = new QStandardItemModel(this);

model->setColumnCount(2);
model->appendRow(items);

See http://doc.qt.io/qt-5/qstandarditemmodel.html#appendRow for more detail.