具有QAbstractListModel的QListView显示一个空列表 [英] QListView with QAbstractListModel shows an empty list

查看:128
本文介绍了具有QAbstractListModel的QListView显示一个空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用自定义的QAbstractListModel创建了一个非常简单的QListView示例.显示QListView,但它为空.

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

我在做什么错了?

代码:

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

谢谢!

对先前代码的修复是将模型的父级设置为QListView:

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?

推荐答案

仅当role = Qt :: DisplayRole时,您的方法数据才应返回"a".否则,它将为每个角色返回"a".

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

这篇关于具有QAbstractListModel的QListView显示一个空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆