0

我需要在 BB 10 中使用动态数据实现可折叠列表。为此,我使用 Github 中提供的 FilteredDataModel 示例。目前示例中的所有数据都是硬编码的,但需要在 ListView 中动态填充数据。

搜索了很多,但没有得到任何东西。

4

1 回答 1

0

我看了一下那个例子,硬编码的数据在 VegetablesDataModel::data 函数中。这就是您想要用动态数据替换的数据。

首先,您需要考虑如何存储数据。该列表有标题,每个标题都有一个子列表。表示标题和项目子列表的一种方法是使用

QPair<QString, QList<QString> >

QPair::first 将是您的标题,QPair::second 将是子项列表。

为了使键入更容易,您可以使用 typedef

typedef QPair<QString, QList<QString> > SubList;

然后要表示 ListView 中的所有数据,您需要上面的 SubList 结构的列表

QList<SubList>

接下来,我们要替换蔬菜数据模型返回数据的方式。为上述项目列表添加一个新的成员变量到 VegetablesDataModel

QList<SubList> m_listData.

您现在只需替换​​ VegetablesDataModel::data 和 VegetablesDataModel::childCount 函数的内容。

QVariant VegetablesDataModel::data(const QVariantList& indexPath)
{
    QString value;

    if (indexPath.size() == 1) { // Header requested
        int header = indexPath[0].toInt();
        return m_listData[header].first; // Return the header name
    }

    if (indexPath.size() == 2) { // 2nd-level item requested
        const int header = indexPath[0].toInt();
        const int childItem = indexPath[1].toInt();
        return m_listData[header].second[childItem]; // Return the matching sublist item.

    }

    qDebug() << "Data for " << indexPath << " is " << value;

    return QVariant(value);
}

这会处理数据,但我们仍然需要告诉 listView 我们有多少元素。

int VegetablesDataModel::childCount(const QVariantList& indexPath)
{

    const int level = indexPath.size();

    if (level == 0) { // The number of top-level items is requested
        return m_listData.length();
    }

    if (level == 1) { // The number of child items for a header is requested
        const int header = indexPath[0].toInt();
        return m_listData[header].second.length();
    }

    // The number of child items for 2nd level items is requested -> always 0
    return 0;
}

你应该很好,其他一切都保持不变。剩下的就是让您用您想要的数据填写 m_listData。请注意任何拼写错误,因为我没有机会测试我的代码,但逻辑应该在那里。

于 2013-07-26T02:04:39.013 回答