Search code examples
javascriptqtfrontendqmlqtquick2

Is it possible to choose between Delegates in QML using Javascript logic?


currently I have a Repeater Item which loads a delegate from an external file (PeriodicTableDelegate.qml). Is it possible to choose between lets say two different Delegates using Javascript logic? Maybe like this for example:

Normal :

Repeater {
    model: elementModel
    
    delegate: PeriodicTableDelegate {
    height: gridview.cellHeight
    selectionModel: itemSelectionModel
    width: gridview.cellWidth
    x: (group - 1) * width
    y: (period - 1) * height
    }          
}                  
               

How I would want it to work:

Repeater {
    model: elementModel
    
    delegate: pickDelegate() ? PeriodicTableDelegate : SomeOtherDelegate {
    height: gridview.cellHeight
    selectionModel: itemSelectionModel
    width: gridview.cellWidth
    x: (group - 1) * width
    y: (period - 1) * height
    }          
}
function pickDelegate(){
   return window.height > 60
}

Solution

  • The answer is yes. As mentioned in the comments, there are lots of ways to do it, but what you wrote in your question is already almost working. The only thing missing is you probably want to declare your delegates as Components. And while a function can work for your conditional, it makes more sense to use a declarative style relying on property bindings.

    Component {
        id: periodic
        PeriodicTableDelegate {
            // initialize stuff
        }
    }
    
    Component {
        id: other
        SomeOtherDelegate {
            // initialize stuff
        }
    }
    
    property bool someCondition: window.height > 60
    
    Repeater {
        model: elementModel
        delegate: someCondition ? periodic : other
    }