Unable to call function in qml, defined in c++ file



  • Here is a sample code example

    main.qml

    import QtQuick 2.3
    import QtQuick.Controls 1.2
    ApplicationWindow {
        id: aw
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
        // Some interaction elements
        Text {
            id: someTxt
            text: qsTr("Hello World")
            anchors.centerIn: parent
        }
        Button {
            id: someBtn
            text: qsTr("someButton")
            anchors.centerIn: parent
            anchors.verticalCenterOffset: -40
            onClicked: {
                // Default button signal
                testObject.someSlot("fn-call")
            }
        }
        // Create connections with c++
        Connections             // Define actions for custom slots
        {
            id:cppConnection
            target:testObject
            ignoreUnknownSignals: true
            onSomeSignal: {
                console.log("Hello Qml");
                  // To access signal parameter, name the parameter
                someTxt.text = text
           }
        }
    }
    

    and main.cpp file is here:

    #include <QApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlContext>
    #include "testobject.h"
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
        QQmlApplicationEngine engine;
        TestObject to;
        // Load the QML and set the Context
        engine.rootContext()->setContextProperty("testObject",&to);
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        return app.exec();
    }
    

    testObject.h

    #ifndef TESTOBJECT_H
    #define TESTOBJECT_H
    
    #include <QObject>
    
    class TestObject : public QObject
    {
        Q_OBJECT
    public:
        explicit TestObject(QObject *parent = 0);
    
    signals:
        void someSignal(const QString &text);
    
    public slots:
        void someSlot(const QString &text);
    
    };
    
    #endif // TESTOBJECT_H
    
    

    and testObject.cpp file is here

    #include "testobject.h"
    #include <QString>
    #include <QDebug>
    TestObject::TestObject(QObject *parent) :
        QObject(parent)
    {
    }
    void TestObject::someSlot(const QString &text)
    {
        QString nText = text + ".cpp";
        emit someSignal(nText);
        qDebug()<< "Hello Cpp";
        qDebug() << nText;
    }
    
    

    This project executes nicely. When i try to apply the same concept in another big project, the project is crashing and displaying forced unexpectedly and the following code is as shown:

    NTMouseEvents.cpp

    #include "NTMouseEvents.h"
    #include <QString>
    #include <QDebug>
    
    NTMouseEvents::NTMouseEvents(QObject *parent) : QObject(parent)
    {
    
    }
    void NTMouseEvents::somePrintSlot(const QString &text)
    {
        qDebug() << "Printing somePrintSlot";
        QString nText = text + ".cpp";
        qDebug() << text;
    }
    
    

    NTMouseEvents.h

    #ifndef NTMOUSEEVENTS_H
    #define NTMOUSEEVENTS_H
    
    #include <QObject>
    
    class NTMouseEvents : public QObject
    {
        Q_OBJECT
    public:
        NTMouseEvents(QObject *parent = 0);
    public slots:
        void somePrintSlot(const QString &text);
    };
    
    #endif // NTMOUSEEVENTS_H
    
    

    Inside my Gui.cpp file

    NTMouseEvents ntme;
    m_mainView->rootContext()->setContextProperty(QStringLiteral("ntmouseevents"),        QVariant :: fromValue(&ntme));
    

    and when i use this in my qml file as

    ntmouseevents.somePrintSlot("hello");
    

    The program crashes at particular location of my qml file, giving segmentation fault. Why is my program crashing? And how can i interface c++ and qml files?


  • Moderators

    @JennyAug13 said in Unable to call function in qml, defined in c++ file:

    QVariant :: fromValue(&ntme));

    That looks suspicious. Use just &ntme without the QVariant bit.



  • @sierdzio nope, i get the same error and app is crashing though i removed the QVariant.


  • Moderators

    @JennyAug13 said in Unable to call function in qml, defined in c++ file:

    Inside my Gui.cpp file
    NTMouseEvents ntme;
    m_mainView->rootContext()->setContextProperty(QStringLiteral("ntmouseevents"), QVariant :: fromValue(&ntme));

    that is not inside your main.cpp right?

    because I think your NTMouseEvents - object goes out of scope pretty quickly as it is not a member of your class and not created on the heap.



  • @J.Hilk Yes, it is not inside my main.cpp file.. Okay i will try to give it in my main.cpp file. But in my main.cpp file i have following lines of code.

     QMetaObject::invokeMethod(&gui, "showMainView",  Qt::QueuedConnection);
    

    where

    showMainView() 
    

    is inside my gui.cpp file and i have my NTMouseEvents ntme; inside this function definition.


  • Moderators

    The point is that once that function exits, it will destroy your ntme object. So, use heap like @J-Hilk said.



  • @J.Hilk I changed now to main.cpp file as follows:

    #include "Components/NTMouseEvents.h"
    ..
    ..
    ..
    int main(int argc, char *argv[])
    {
    .....
    ....
    
       NTMouseEvents ntme;
       engine.rootContext()->setContextProperty(QStringLiteral("ntmouseevents"),        QVariant :: fromValue(&ntme));
    .....
    .....
       return app.exec();
    }
    

    but i am getting following error inside my qml file and i have used following line of code inside my qml file

    ntmouseevents.somePrintSlot("hello");
    
     qrc:///QML/Components/BigButton.qml:325: ReferenceError: ntmouseevents is not defined
    
    

    Should i load my qml file inside my main.cpp file like they have loaded main.qml file in main.cpp file of test project mentioned in the top but

    ntmouseevents.somePrintSlot("hello");
    

    this is not inside my main.qml file but it is inside my BigButton.qml file.


  • Moderators

    Root context is visible from any QML file loaded by the same engine. Do you have 2 QQmlEngines in your C++ code?



  • Yes i have rootContext in one of the files as follows

    private:
     QQuickView *                    m_mainView;
    ....
    ....
    m_mainView->rootContext()->setContextProperty(QStringLiteral("Gui"),          QVariant(Gui));
    

    also in another file called gui.cpp file

    and in another file called modelDB.cpp file, it is as follows

    #include <QQmlEngine>
    ....
    ....
    ....
    QQmlEngine::setObjectOwnership(inst, QQmlEngine::CppOwnership);
    
    

    Like this in another cpp files, QQmlEngine is being used


  • Qt Champions 2017

    @JennyAug13 said in Unable to call function in qml, defined in c++ file:

    ntmouseevents

    This issue clearly indicates the ntmouseevents object does not exist in your context. Can you show the complete code in your main.cpp ? It is possible that ntime object is within the block of code and it is deleted. In order to check this try the following.

    1. Have destructor in NTMouseEvents class. Place some debug statement. Just check whether object is getting destroyed.

    2. Create the object dynamically like the following.

    NTMouseEvents *ntme = new NTMouseEvents;
    engine.rootContext()->setContextProperty("nttmousge",ntme);
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.