簡體   English   中英

無法從 qml 調用 c++ 方法:“對象的屬性不是函數”

[英]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”

有誰知道如何解決這個問題?

非常感謝!

Mabe 相關,但我沒有找到解決方案

主程序

#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");
        }
    }
}

Window它有一個名為data的屬性,因此您不應該使用該名稱,因為可以理解數據是指該屬性而不是您傳遞給它的對象。

解決辦法是改名:

C++

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

QML:

helper.test("test");

另一方面,如果您要使用setContextProperty() ,則不需要注冊類型。

問題可能是您將上下文屬性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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM