【问题标题】:qabstractitemmodel data not changing in qmlqabstractitemmodel 数据在 qml 中没有改变
【发布时间】:2023-03-04 09:33:02
【问题描述】:

我复制了 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】:

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

    另一方面,您在 cmets 中指出 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多