Search code examples
qtqmlqlistview

Complex logic which produces true/false to control visibility


I have the following QML code:

ListView {
    model: ListModel {
        ListElement {
            eleText: "Me"
            eleFirst: true
            eleSecond: true
        }
        ListElement {
            eleText: "My GF"
            eleFirst: false
            eleSecond: false                         
        }
        ListElement {
            eleText: "Ben Dover"
            eleFirst: true
            eleSecond: false
        }
    }
    delegate: Row {
        visible: true
        Label: eleText
    }
}

I intend to have a complex logic to control the visibility of each row on my ListView. I mean, to set the visible: field, I like to have this complex logic:

if( someObject.getStatus() == "first" ) {
    if (eleFirst) {
        return true;
    } else {
        return false;
} else if ( someObject.getStatus() == "second" ) {
    if (eleSecond) {
        return true;
    } else {
        return false;
    }
} else {
    // Should not get here
    // throw errors
}

How can I use such a complex logic to control the visibility of my ListView rows?


I have to use Qt 5.9.4


Solution

  • If you want a complex model, subclass the QAbstractListModel. There you can define your own role for visibility and whatever logic you need. Alternatively shorten your logic to a ternary operator.