问题
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