c++ - qabstractitemmodel 数据在 qml 中没有改变

标签 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

谢谢。

最佳答案

问题是因为 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);
}

关于c++ - qabstractitemmodel 数据在 qml 中没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55424368/

相关文章:

c++ - 如何对依赖 Asio 的一段代码进行单元测试?

python - PyEval_CallObject 和 PyObject_CallObject 返回一个空对象

c++ - 为什么在rapidjson中调用赋值运算符后成员变量发生变化?

c++ - Qt 和 CMake 因重复符号而失败

c++ - 在具有多个 View 的 QML 中查看、编辑和更新数据(来自 C++),而数据保留在 C++ 中(订阅数据)

c++ - Boost graph typedef c++ 结构的前向声明

c++ - Qt5 QWidget :hover effect delay

json - 如何在 QT 中将 JSON 字符串格式化为可读输出

qt - QML ListView : How to disable autoscrolling when new elements inserted?

qml - 子元素能否均匀填充Grid?