簡體   English   中英

qabstractitemmodel數據在qml中未更改

[英]qabstractitemmodel data not changing in qml

我已經復制了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)或更好地只是指示用index(0)更新了第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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM