2

Say I have a QML Application with a toolbar:

ApplicationWindow {
  header: MyTools {
    showAdminButtons: userIsAdmin()
  }
}

I can dynamically pick the component to show by using a Loader:

ApplicationWindow {
  header: Loader {
    source: Qt.platform.os=="linux" ? "qrc:/linux/MyTools.qml" : "qrc:/MyTools.qml"
  }
}

However, if I want to supply custom property values to that component (like showAdminButtons above), I must use the setSource() method:

ApplicationWindow {
  header: Loader {
    Component.onCompleted: {
      var qml = Qt.platform.os=="linux" ? "qrc:/linux/MyTools.qml" : "qrc:/MyTools.qml";
      setSource( qml, {showAdminButtons:userIsAdmin()} );
    }
  }
}

Is there a "QML-only" way to supply properties to a Loader, that does not require Component.onCompleted? (I cannot fully justify why Component.onCompleted feels like a gross hack workaround to me, but it does, every time I have to use it. It's something to do with the declarative nature of QML vs. the procedural nature of JS.)

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • I've discovered [this answer](http://stackoverflow.com/a/27704424/405017) which sort of solves my question. However, it appears to work only if I remove properties from my components' signatures and instead define them to require the instantiation to pass values in. It prevents property aliases and default values from working. – Phrogz Aug 15 '16 at 16:53
  • 1
    A technique called "file selectors" is superior compared to Loader + Qt.platform.os: http://www.ics.com/blog/mastering-qt-file-selectors – jpnurmi Aug 15 '16 at 21:30

1 Answers1

6

Method 1: binding (or a simple assignment if binding is not necessary) when Loader.onLoaded:

ApplicationWindow {
    header: Loader {
        source: Qt.platform.os=="linux" ? "qrc:/linux/MyTools.qml" : "qrc:/MyTools.qml"
        onLoaded: {
            item.showAdminButtons = Qt.binding(function() { return userIsAdmin(); }
        }
    }
}

Method 2: use Binding type:

ApplicationWindow {
    header: Loader {
        id: loader
        source: Qt.platform.os=="linux" ? "qrc:/linux/MyTools.qml" : "qrc:/MyTools.qml"
        Binding {
            target: loader.item
            property: "showAdminButtons"
            value: userIsAdmin()
        }
    }
}
BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
mcchu
  • 3,309
  • 1
  • 20
  • 19