Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send argument while opening a popup QML

I’m trying to open a popup and pass an argument that will be displayed as part of the popup. I can do that by creating a property and just changing the property right before I open the popup, but I’m wondering if I can accomplish this without making a property and by somehow passing an argument to the popup? Basically accomplish this without creating a property:

import QtQuick 2.15
import QtQuick.Window 2.2
import QtQuick.Controls 2.15

Window {
    id: window
    visible: true
    height: 400
    width: 400
    property var username: "Morbius"

    Button {
        text: "Click me"
        onClicked: {
            username = "Definitely not Morbius"
            popup.open()
        }
    }

    Popup {
        id: popup
        width: 220
        height: 200
        closePolicy: Popup.CloseOnPressOutside
        Text {
            id: name
            text: "Hello, " + username
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Well, you need a way to store the value you’re passing in, so a property is the natural choice. But I would make the property a part of the Popup, not the parent window. That way you can reuse it in other places too. And you could make it look a little prettier with a custom open() function.

Window {
    id: window

    Button {
        text: "Click me"
        onClicked: {
            popup.openMe("Definitely not Morbius")
        }
    }

    Popup {
        id: popup
        property string username

        function openMe(name) {
            username = name;
            open();
        }

        Text {
            id: name
            text: "Hello, " + username
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading