Important: Please read the Qt Code of Conduct -

Function parameters QML/C++

  • Hello,

    In order to communicate between my QML UI and my C++ code, I use ContextProperty.
    For instance, in my main.cpp, I have my main function:

    int main(int argc, char *argv[])
        QApplication app(argc, argv);
        QQmlApplicationEngine engine;
        QQmlComponent componentmain(&engine,QUrl(QStringLiteral("qrc:/main.qml")));
        QQmlContext* ctx = engine.rootContext();
        OtherFunctions otherfunctions;
        ctx->setContextProperty("otherfunctions", &otherfunctions);
        testmainfunc(otherfunctions); // explained later
        return app.exec();

    From my QML code, I can access the functions from my class "otherfunctions". I can also access this class from my main function which is usefull to communicated between QML and C++.

    However, in my main.cpp, I have another function that I call from the main function: testmainfunc(otherfunctions). As a parameter, I want to send my class "otherfunctions" so this function can modify parameters from "otherfunctions" and thus communicate with the QML code.

    However, when I declare my function as "void testmainfunc(OtherFunctions otherfunctions);", I get the error :
    "error: use of deleted function 'OtherFunctions::OtherFunctions(const OtherFunctions&)'"

    If I declare my function as "void testmainfunc(OtherFunctions &otherfunctions);" [notice the &] it seems fine. For instance the following seems to work:

    void testmainfunc(OtherFunctions &otherfunctions)

    My question is

    1. Why "void testmainfunc(OtherFunctions otherfunctions);" does not work ?
    2. Is it OK to do as I did with "void testmainfunc(OtherFunctions &otherfunctions);" [notice the &] ?

    Thank you very much for your help !


  • Qt Champions 2017

    Your object is Qobject. You r passing the object by value. Copy constructor is disabled in qt. Hence you hit the error.

  • Qt Champions 2019

    @alecs26 To add to @dheerendra : if you want a function which modifies its parameter then you should pass this parameter as reference (&) or pointer (*), else your function will modify a copy! Read about passing parameters "by value", "by reference" and pointer in C++.

  • @jsulm
    Thank you for you answer.

    So is it OK to do that:
    in the main call: testmainfunc(otherfunctions);

    and the function:
    void testmainfunc(OtherFunctions &otherfunctions)

    Thank you !


  • Qt Champions 2019

    @alecs26 Actually you can answer your own question by just trying it out.
    But, yes passing by reference will work.

  • Qt Champions 2017

    Yes it is ok as you r passing the object by reference.

  • @jsulm @dheerendra
    Thank you for your answer.

    @jsulm Yes I tried it and it worked but I wanted to be sure it was a proper way to do it.

    Thank you both very much !


Log in to reply