qabstractitemmodel数据在qml中没有变化

问题描述 投票:1回答:1

我已经复制了Qt示例动物qabstractitemmodel并尝试在QML中显示它并更改值。我已经为模型添加了一个函数来做到这一点

Q_INVOKABLE void change()
{
     m_animals.first().m_size="newValue";
     // setData(this->index(0), "newValue", SizeRole); //always returns false, has no effect if uncommented
     qDebug() << this->data(this->index(0), SizeRole); //returns correctly new value as set in previous uncommented line

     emit dataChanged(this->index(0), this->index(this->rowCount()), {SizeRole}); // the value in QML is not updated at any point
}

为什么QML中的值没有更新?

我上传了完整的样本

https://ufile.io/jfflj

谢谢。

c++ qt qml qt5 qabstractitemmodel
1个回答
0
投票

问题是因为index(rowCount())是QModelIndex无效,而你必须使用index(rowCount()- 1)或更好只是指示第0行用index(0)更新:

Q_INVOKABLE void change()
{
    m_animals.first().m_size="newValue";
    qDebug() << this->data(this->index(0), SizeRole);
    emit dataChanged(index(0), index(rowCount()-1), {SizeRole});
    // or better
    // emit dataChanged(index(0), index(0), {SizeRole});
}

另一方面,你在评论中指出setData()总是返回false,这是正确的,因为当使用QAbstractListModel()类作为基础时,你必须实现该方法:

bool AnimalModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(!index.isValid()) return false;
    if (index.row() < 0 || index.row() >= rowCount()) return false;
    Animal & animal =  m_animals[index.row()];
    if(role == TypeRole)
        animal.m_type = value.toString();
    else if(role == SizeRole)
        m_animals[index.row()].m_size = value.toString();
    else
        return false;
    emit dataChanged(index, index, {role});
    return true;
}

然后你可以使用它:

Q_INVOKABLE void change()
{
    setData(index(0), "newValue", SizeRole);
}
© www.soinside.com 2019 - 2024. All rights reserved.