Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically add data to QTableView

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.

like image 684
aj3423 Avatar asked Nov 15 '13 05:11

aj3423


1 Answers

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 QVariants, so there's no need to callQVariant::fromValue()

Also if you're using Qt, you would normally be using QStrings, not std::strings.

like image 102
Chris Avatar answered Oct 05 '22 23:10

Chris