Question

I've created an implementation of the QAbstractListModel class in Qt Jambi 4.4 and am finding that using the model with a QListView results in nothing being displayed, however using the model with a QTableView displays the data correctly.

Below is my implementation of QAbstractListModel:

public class FooListModel extends QAbstractListModel
{
    private List<Foo> _data = new Vector<Foo>();

    public FooListModel(List<Foo> data)
    {
        if (data == null)
        {
            return;
        }

        for (Foo foo : data)
        {
            _data.add(Foo);
        }

        reset();
    }

    public Object data(QModelIndex index, int role)
    {
        if (index.row() < 0 || index.row() >= _data.size())
        {
            return new QVariant();
        }

        Foo foo = _data.get(index.row());

        if (foo == null)
        {
            return new QVariant();
        }

        return foo;
    }

    public int rowCount(QModelIndex parent)
    {
        return _data.size();
    }
}

And here is how I set the model:

Foo foo = new Foo();
foo.setName("Foo!");

List<Foo> data = new Vector<Foo>();
data.add(foo);

FooListModel fooListModel = new FooListModel(data);
ui.fooListView.setModel(fooListModel);
ui.fooTableView.setModel(fooListModel);

Can anyone see what I'm doing wrong? I'd like to think it was a problem with my implementation because, as everyone says, select ain't broken!

Was it helpful?

Solution

I'm not experienced in Jambi, but shouldn't you be returning a QVariant from method data() instead of returning a Foo? It's not clear to me how the view is going to know how to convert the Foo into a string for display.

Also, any chance I could sell you the easier-to-use QStandardModel and QStandardModelItem instead of rolling a fully custom one the hard way? And if you are only going to have one view ever, you can avoid the whole MVC Pattern altogether and just use the very very easy to use QListWidget.

OTHER TIPS

Your model's data() implementation has two problems in it:

  • It fails to different values for different item data roles. Your current implementation returns the same value for all roles, and some views can have problems with it.

  • QVariant in Jambi is not the same as in regular Qt. When you have nothing to return,
    just return null.

A better implementation would be:

public Object data(QModelIndex index, int role) {
    if (index.row() < 0 || index.row() >= _data.size())
        return null;

    if (role != Qt.ItemDataRole.DisplayRole)
        return null;

    return _data.get(index.row());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top