gpt4 book ai didi

c++ - 从 C++ 调用组件中定义的 QML 函数

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:01 25 4
gpt4 key购买 nike

让我们在 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()。

因此,如果您需要更多帮助,您需要发布更多代码来帮助重现问题。

我的代码如下...

A.qml

import QtQuick 2.7

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

B.qml

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

助手.h

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

关于c++ - 从 C++ 调用组件中定义的 QML 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46635892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com