I'm writing a simple TableView
according to
http://harmattan-dev.nokia.com/docs/library/html/qt4/itemviews-addressbook.html
class MyModel : public QAbstractTableModel {
Q_OBJECT
public:
QList<QPair<string, int> > data_;
....
How to add rows to the model dynamically? data_.insert(..)
won't change the view, currently I write a function to append new row:
void my_append_data(const string& first, int second) {
int row = rowCount(QModelIndex());
insertRow(row); // insert a empty row
// fill the row
setData(createIndex(row, 0), QVariant::fromValue<string>(first), Qt::EditRole);
setData(createIndex(row, 1), QVariant::fromValue<int>(second), Qt::EditRole);
}
// usage
model.my_append_data("11111", 111);
model.my_append_data("22222", 222);
This seems inefficient cause the setData
is called twice when append a row, because there're two columns, and there may be more columns in the future.
Any better way to append rows?
Thanks.
I'm not sure why you think it's inefficient. However you could make it simpler.
I would probably write your function like this, which would make it more future proof against changes to column counts and types:
void my_append_data(const QVariantList &data) {
insertRow(rowCount(QModelIndex()));
foreach(const QVariant &item, data) {
setData(createIndex(row, 0), item, Qt::EditRole);
}
}
Usage:
model.my_append_data(QVariantList() << "11111" << 111);
Basic (and most Qt types) can be implicitly converted into QVariant
s, so there's no need to callQVariant::fromValue()
Also if you're using Qt, you would normally be using QString
s, not std::string
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With