Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. Unable to call function in qml, defined in c++ file
Forum Updated to NodeBB v4.3 + New Features

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

Scheduled Pinned Locked Moved Unsolved QML and Qt Quick
10 Posts 4 Posters 1.7k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    JennyAug13
    wrote on 4 Jan 2019, 11:25 last edited by JennyAug13 1 Apr 2019, 11:26
    #1

    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?

    S J 2 Replies Last reply 4 Jan 2019, 11:57
    0
    • J JennyAug13
      4 Jan 2019, 11:25

      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?

      S Offline
      S Offline
      sierdzio
      Moderators
      wrote on 4 Jan 2019, 11:57 last edited by
      #2

      @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.

      (Z(:^

      J 1 Reply Last reply 4 Jan 2019, 12:20
      0
      • S sierdzio
        4 Jan 2019, 11:57

        @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.

        J Offline
        J Offline
        JennyAug13
        wrote on 4 Jan 2019, 12:20 last edited by
        #3

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

        1 Reply Last reply
        0
        • J JennyAug13
          4 Jan 2019, 11:25

          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?

          J Offline
          J Offline
          J.Hilk
          Moderators
          wrote on 4 Jan 2019, 12:48 last edited by J.Hilk 1 Apr 2019, 12:48
          #4

          @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.


          Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


          Q: What's that?
          A: It's blue light.
          Q: What does it do?
          A: It turns blue.

          J 2 Replies Last reply 4 Jan 2019, 13:54
          3
          • J J.Hilk
            4 Jan 2019, 12:48

            @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 Offline
            J Offline
            JennyAug13
            wrote on 4 Jan 2019, 13:54 last edited by
            #5

            @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.

            1 Reply Last reply
            0
            • S Offline
              S Offline
              sierdzio
              Moderators
              wrote on 4 Jan 2019, 13:59 last edited by
              #6

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

              (Z(:^

              1 Reply Last reply
              2
              • J J.Hilk
                4 Jan 2019, 12:48

                @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 Offline
                J Offline
                JennyAug13
                wrote on 4 Jan 2019, 14:21 last edited by JennyAug13 1 Apr 2019, 14:23
                #7

                @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.

                1 Reply Last reply
                0
                • S Offline
                  S Offline
                  sierdzio
                  Moderators
                  wrote on 4 Jan 2019, 20:10 last edited by
                  #8

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

                  (Z(:^

                  1 Reply Last reply
                  0
                  • J Offline
                    J Offline
                    JennyAug13
                    wrote on 5 Jan 2019, 01:59 last edited by JennyAug13 1 May 2019, 02:18
                    #9

                    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

                    1 Reply Last reply
                    0
                    • dheerendraD Offline
                      dheerendraD Offline
                      dheerendra
                      Qt Champions 2022
                      wrote on 5 Jan 2019, 15:53 last edited by
                      #10

                      @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);
                      

                      Dheerendra
                      @Community Service
                      Certified Qt Specialist
                      http://www.pthinks.com

                      1 Reply Last reply
                      2

                      1/10

                      4 Jan 2019, 11:25

                      • Login

                      • Login or register to search.
                      1 out of 10
                      • First post
                        1/10
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • Users
                      • Groups
                      • Search
                      • Get Qt Extensions
                      • Unsolved