简体   繁体   中英

Cannot invoke c++ method from qml: "Property of object is not a function"

I am now trying to find a solution for hours and I absolutely have no clue what is wrong.

I am trying to submit a string from QML to a C++ method and I get the error: "qrc:/main.qml:16: TypeError: Property 'test' of object [object Object] is not a function"

Has anyone an idea how to fix that?

Thank you very much!

Mabe related but I do not find a solution

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "data.h"
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    qmlRegisterType<Data>("com.br.classes", 1, 0, "Data");

    Data* myData = new Data();

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("data", myData);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
 }

data.h

#ifndef DATA_H
#define DATA_H

#include <QObject>
#include <QDebug>

class Data : public QObject
{  
    Q_OBJECT
public:
    explicit Data(QObject *parent = nullptr);

    Q_INVOKABLE void test(QString strg) {qDebug() << "Received string: " << strg;}
};

#endif // DATA_H

main.qml

import QtQuick 2.7
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import com.br.classes 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Button {
        text: "Press me!"
        onClicked: {
            data.test("test");
        }
    }
}

Window it has a property called data , so you should not use that name since it will be understood that the data refers to that attribute and not to the object that you are passing on to it.

The solution is to change the name:

C++

engine.rootContext()->setContextProperty("helper", myData);

QML:

helper.test("test");

On the other hand it is not necessary to register the type if you are going to use setContextProperty() .

The issue is probably that you named the context property data , which is already a property of Item . Call the property something else and it should work.

better you create an object of that class in QML code and then use its functions.

your main.qml

import QtQuick 2.7
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import com.br.classes 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Data { id: data }

    Button {
        text: "Press me!"
        onClicked: {
            data.test("test");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM