Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Dynamically reference QML components



  • I would like to use the string returned from key.event.text to dynamically reference the component that has a matching id.

    I could have many different components with id's that I don't know of which is why I am trying to make this dynamic, hence the commented out switch statement.

    import QtQuick 2.15
    import QtQuick.Window 2.15
    
    Window {
        width: 300
        height: 300
        visible: true
    
        Item {
            focus: true
            Keys.onPressed: {
                rect_id = event.text
                rect_id.color = 'red'
    
                // switch (event.text) {
                //     case 'q':
                //         q.color = 'red'
                //         break;
                //     case 'w':
                //         w.color = 'red'
                //         break;
                // }
            }
        }
        Row {
            Rectangle {
                id: 'q'
                width: 50
                height: 50
                border.color: '#000'
                border.width: 1
                color: 'transparent'
            }
    
            Rectangle {
                id: 'w'
                width: 50
                height: 50
                border.color: '#000'
                border.width: 1
                color: 'transparent'
            }
        }
    
    }
    


  • property var dict = ({
      'q' : q
      'w' : w
    })
    
    Item {
      id: q
      function func1(){}
    }
    Item {
      id: w
      function func1(){}
    }
    

    Access them:

    dict['w'].func1()
    


  • property var dict = ({
      'q' : q
      'w' : w
    })
    
    Item {
      id: q
      function func1(){}
    }
    Item {
      id: w
      function func1(){}
    }
    

    Access them:

    dict['w'].func1()
    


  • Thanks! Works


Log in to reply