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

How to refer to a QML file component?



  • The TabView type has an addTab method whose second argument is a component type. If I define a component inline, using the Component type, I can give it an id, and pass the id to addTab. That's what's shown in the documentation examples.

    But what if the component is defined by a QML file? How do I pass it to addTab? Using the name of the file without the .qml suffix doesn't bother the compiler, but at run-time it complains ".../TabView.qml:143: Error: Cannot assign null to QQmlComponent*".


  • Moderators

    Not sure but this should work:

    Component {
      id: myTab
      YourQmlFileName {
      }
    }
    
    // in tab view:
    addTab("Title", myTab)
    

  • Moderators

    @pderocco said in How to refer to a QML file component?:

    But what if the component is defined by a QML file? How do I pass it to addTab?

    see this

    var comp = Qt.createComponent("MyComponent.qml");
    


  • @sierdzio @raven-worx Thanks. Both methods seem to work.

    I assumed that Component created another object around what was generated by the QML file, and would require property aliases to bridge between the two, but that's not the case.

    As it turns out, though, using Component is more appropriate in my case, because it provides an opportunity to customize it. My component is a simple HTML help viewer, which handles links internally, but emits a newTab signal when a link is long-pressed, so I can write:

    Component {
        id: htmlPage
        HtmlPage { onNewTab: createNewTab(url) }
    }
    

    rather than build the createNewTab call into the HtmlPage object.


Log in to reply