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

How to Load Another Qml file?



  • Hi Guys,

    I have a simple Qt Quick project with 2 Qml files called "main.qml" and "Second.qml". when i run my app, the "main.cpp" loads and shows "main.qml".

    i want my app show "Second.qml", when user clicked text with id of "form_main_text" that is located in "main.qml", but i don't know how!

    Here are contents of "main.cpp":
    #include <QApplication>
    #include <QQmlApplicationEngine>

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/Second.qml")));
    
    return app.exec();
    

    }

    Here are contents of "main.qml":
    import QtQuick 2.4
    import QtQuick.Controls 1.3
    import QtQuick.Window 2.2

    ApplicationWindow
    {
    title: qsTr("Hello World")
    width: 640
    height: 480
    visible: true

    MainForm {
        id:form_main
        anchors.fill: parent
    
        Text
        {
            id:form_main_text
            anchors.centerIn: parent
            text:"This is Main Form!"
        }
    }
    

    }

    and finally content of "Second.qml":
    import QtQuick 2.4
    import QtQuick.Controls 1.3
    import QtQuick.Window 2.2

    ApplicationWindow
    {
    title: qsTr("Hello World")
    width: 640
    height: 480
    visible: true

    MainForm {
        id:form_second
        anchors.fill: parent
    
        Text
        {
            id:form_second_text
            anchors.centerIn: parent
            text:"This is Second Form!"
        }
    }
    

    }

    thank you and sorry for my bad English.


  • Moderators

    Hi @iMasoud,

    You can do it in following ways:

    • Loader. Add this in main.qml and then set Second.qml as its source when required to load it.
    • Use Qt.createComponent() to load the QML. This is more dynamic approach. More info here.


  • Hi @p3c0 ,

    Thank you for your reply. It really was helpful.


Log in to reply