QListView with QAbstractListModel shows an empty list

喜夏-厌秋 提交于 2019-12-01 02:12:36

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/15104711/qlistview-with-qabstractlistmodel-shows-an-empty-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!