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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With