qabstractitemmodel数据在qml中未更改

时间:2019-03-29 19:30:21

标签: c++ qt qml qt5 qabstractitemmodel

我已经复制了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

谢谢。

1 个答案:

答案 0 :(得分: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);
}