Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QListView with QAbstractListModel shows an empty list

I have created a very simple example of QListView with a custom QAbstractListModel. The QListView is displayed but it is empty.

What am I doing wrong?

Code:

#include <QListView>
#include <QAbstractListModel>
#include <QApplication>

class DataModel: public QAbstractListModel
{
public:
    DataModel() : QAbstractListModel() {}
    int rowCount( const QModelIndex & parent = QModelIndex() ) const { return 2; }
    QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const
    {
        return "a";
    }
};

int main( int argc, char **argv)
{
    QApplication app(argc, argv, true);
    QListView *lv = new QListView();
    DataModel d;
    lv->setModel( &d ); 
    lv->show();
    app.setMainWidget(lv);
    app.exec();
}

Thanks!

The fix to the previous code is to set the parent of the model to the QListView:

DataModel d(lv);

But this raises a question, where is the model/view independence if the model has to have a reference to the view?

What if I want to use this model in two different views?

like image 540
Santilín Avatar asked Feb 27 '13 05:02

Santilín


1 Answers

Your methods data should return "a" only if role = Qt::DisplayRole. Otherwise, it returns "a" for every role.

So, add a simple test and it will work :

  QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const
{
    if ( role == Qt::DisplayRole ) {
      return "a";
    }
    return QVariant();
}
like image 61
Dimitry Ernot Avatar answered Oct 05 '22 12:10

Dimitry Ernot