QStandardItem and int
-
Hi,
Does anyone know if QStandardItem can be used to display int values?I can display it if it's QString
@
QStandardItemModel *model = new QStandardItemModel(0,4,this); //Rows and 4 Columns
ui->tableView->setModel(model);
QStandardItem *firstRow = new QStandardItem(QString("1234"));
model->setItem(0,0,firstRow);
@But if I try this, it doesn't work.
@
QString mystring = "1234";
int myint = mystring.toInt();
qDebug() << "int is" << myint ;QStandardItemModel *model = new QStandardItemModel(0,4,this); //Rows and 4 Columns
ui->tableView->setModel(model);
QStandardItem *firstRow = new QStandardItem(myint);
model->setItem(0,0,firstRow);
@ -
QStandardItem constructor takes displayed text, not the actual model data, so you have (at least) 2 options:
-
The "lazy" approach.
Construct the item like this:
@new QStandardItem(QString::number(myInt));@
The disadvantage is that you need to keep that displayed text with actual data in sync manually. It's ok if it's for one-time displaying. -
The "more proper" way:
Subclass the QStandardItem. Set the int as the custom data with setData(myInt);
Override the data() member and return stringified int for the display role:
@
QVariant MyStandardItem::data(int role) const {
if(role == Qt::DisplayRole)
return data().toString();
else
return QStandardItem::data(role);
}
@
Btw. since you put the items right away you might as well create the row for it right in the constructor of the model:
@ new QStandardItemModel(1,4,this); // 1 row instead of 0@
This avoids resizing of the internal data structure when you add items. -
-
Also keep in mind that if you want to sort on this column it will sort by text which may not always be right. more true for float and time values, so make sure you define the "<" operator for MyStandardItem