[英]Cannot invoke c++ method from qml: "Property of object is not a function"
我現在試圖找到幾個小時的解決方案,我完全不知道出了什么問題。
我試圖將一個字符串從 QML 提交到 C++ 方法,但出現錯誤:“qrc:/main.qml:16: TypeError: Property 'test' of object [object Object] is not a function”
有誰知道如何解決這個問題?
非常感謝!
主程序
#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();
}
數據.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
主文件
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");
}
}
}
問題可能是您將上下文屬性data
命名為已經是Item
的屬性。 將該屬性稱為其他名稱,它應該可以工作。
最好在 QML 代碼中創建該類的對象,然后使用其函數。
你的 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");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.