簡體   English   中英

從C ++調用組件中定義的QML函數

[英]Invoke from C++ a QML function defined in a component

讓我們在A.qml中定義以下組件:

Item {
    function test() { console.log("this is a test") }
}

在B.qml中,我們執行以下操作:

A {
    function test2() { console.log("this is a second test") }
}

在C ++中,我創建一個QQuickView並將源設置為B.qml。 現在,我嘗試調用“測試”,但失敗並顯示一條錯誤消息,指出“ B中不存在測試”。 如果我調用“ test2”,那么一切都會按預期進行。 如果我將test2更改為以下內容:

A {
    function test2() { test() }
}

它成功調用了test()。

問題是,當定義A.qml組件時,如何直接從C ++調用test()函數?

注意:我正在使用Qt 5.7.1

我試圖復制您在Windows 7上使用Qt 5.9.1描述的問題,但無法重現。 我可以從C ++調用test()和test2()。

因此,如果您需要更多幫助,則需要發布更多代碼以幫助重現該問題。

我的下面的代碼...

ml

import QtQuick 2.7

Item {
    function test() { console.log("this is a test") }
}

q

import QtQuick 2.7
import QtQuick.Controls 2.0

A {
    id: root
    function test2() { console.log("this is a second test") }

    Button {
        text: "click me"
        onClicked: {
            helper.invokeMethod(root, "test");
            helper.invokeMethod(root, "test2");
        }
    }
}

助手

#ifndef HELPER_H
#define HELPER_H

#include <QObject>

class Helper : public QObject
{
    Q_OBJECT
public:
    explicit Helper() { }

    Q_INVOKABLE void invokeMethod(QObject* obj, QString method){
         QMetaObject::invokeMethod(obj, method.toLatin1().constData());
    }

signals:

public slots:
};

#endif // HELPER_H

main.cpp

#include <QGuiApplication>
#include <QQmlContext>
#include <QQuickView>
#include "helper.h"

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

    Helper helper;

    QQuickView *view = new QQuickView;
    view->rootContext()->setContextProperty("helper", &helper);
    view->setSource(QUrl("qrc:/B.qml"));
    view->show();

    return app.exec();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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