Important: Please read the Qt Code of Conduct -

Load a .QML with a button ERROR

  • Hi, I am a beginner on Qt and for two days I have a problem that I can not solve. I devellope an application in QML and I would like a page (.qml file) opens thanks to a button, after many researches on forums I found what I needed: QML Loader. Summary of my code:

    Window {
         id : window
         visible: true
         width: Screen.width
         height: Screen.height
         x: 0
         y: 0
                    Button {
                          id: button_1_button
                          x: 0
                          y: 0
                          width: 245
                          height: 61
                          onClicked: loader.source = "window2.qml"
                    Loader {id: loader}

    When I execute my application everything is fine, but when I click on the button, nothing works, it crashes. However, while giving the source directly to the Loader, "window2" opens. I do not know where the problem comes from.

    Thanking you in advance for your proposals =)

    (sierdzio) edit: added missing code tags.

  • Moderators

    If it works with direct source, but not when set via script, I would say it is a Qt bug you've found :-)

    A solution that could work:

    Button {
      onClicked: loader.toggle = !loader.toggle
    Loader {
      id: loader
      property bool toggle: false
      source: toggle? "window2.qml" : undefined

    Some further thoughts:

    • you should (actually you have to) name QML components with a capital letter. So the file should be named "Window2.qml" - this way QML engine will treat it as a component
    • there are other ways to show a new "page": you can use StackView, SwipeView, Dialog, Popup components, for example
    • there is no need to specify x, y positions, they are zero by default
    • for item positioning, it's best to use Layouts, second best - anchors. Manual positioning by x, y and hardcoded dimensions is harder to work with - and also slower in performance

  • Thank you for your answer, I ended up finding the solution to my problem. The .qml file contained a window and loaded another .qml which was also a window. I replaced the loaded .qml window with a page and now everything works!

Log in to reply