0

A little question, I used QAbstractListModel for providing data to QML properties, the first 2 string properties assignments were OK, but when I tried to assign a bool QML property, the assignment failed. My codes are like the following:

ListView
        model: MyModel
        delegate:
        MyItem {
        test: MyModel.isRunning   //test is the bool property and isRunning is the bool role in MyModel
        MouseArea{
              anchors.fill: parent
              onClicked: {
              MyModel.setisRunning(index,boolFlag)  //invert MyModel.isRunning

       }
    }

In MyModel Class I have the following related codes:

void MyModel::setisRunning(int itemIndex, bool isRunning)
{
    mItem[itemIndex]->setRunningState(isRunning);
    emit dataChanged(index(itemIndex,2), index(itemIndex,2),QVector<int>() << TimerRole);
}

and in MyItem Class I have the following related codes:

void MyItem::setRunningState(bool isRunning)
{
   if(isRunning!=m_isRunning)
    {
       m_isRunning = isRunning;
    }

}

I couldn't invert the test property's bool state after I changed MyModel.isRunning, test property always showed "false" when I printed it out.

What confused me most was by executing TimerModel.setisRunning(index,boolFlag), MyModel.isRunning can switch between true/ false, but test property cannot change accordingly I am new to Qt, please help me out! Thank you

WSL
  • 13
  • 6
  • What should we understand from the code you've provided? Please provide [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – folibis Apr 22 '19 at 14:41
  • Sorry, I edited my question – WSL Apr 22 '19 at 14:57
  • @WSL provide a [mcve], your current code is not, because what you show can not reproduce the problem you are pointing out – eyllanesc Apr 22 '19 at 15:05
  • The problem maybe was that I didn't re-implement setData(), I just emitted the dataChange() signal?? – WSL Apr 22 '19 at 16:07

1 Answers1

0

I tried re-implementing setData() in Cpp data model, it worked. Since I didn't re-implement setData(), based on my understanding, the changes in cpp were not "registered" in QML, is this understanding correct?

But I used the approach without setData() (my previous approach, the one only with the dataChange() signal) to change the data in cpp, the QML string property could change accordingly, I cannot understand why that worked?

//change data in cpp
void MyModel::setTime(int itemIndex)
{
    mItem[itemIndex]->setTime(QDateTime::currentDateTime());
    emit dataChanged(index(itemIndex,0), index(itemIndex,0),QVector<int>() << TimerRole);

}

//in QML
   time: Qt.formatTime(model.time, "hh:mm:ss")
WSL
  • 13
  • 6
  • Also,I would like to introduce this approach https://stackoverflow.com/questions/39386697/making-qlistqobject-c-model-dynamic-in-qml which I think is more elegant and easier, but I don't know why it's not introduced in Qt's official tutorials? – WSL Apr 23 '19 at 20:34