我在 QML 中有一个 JavaScript 函数,它创建并返回一个组件 (Item
):
function addMyComponent() {
var component = Qt.createComponent('MyComponent.qml');
var obj = component.createObject(container, {'x': 0, 'y': 0});
return obj; // Not sure weather to return obj or component for my C++ to use
}
我在 main.qml
中也有一些 QML,它使用我制作的自定义 C++ 类:
// ...
import com.acidic.customclass 1.0
import "AddMyComponent.js" as AddMyComponent
ApplicationWindow {
visible: true
width: 1280
height: 800
CustomClass {
id: customClass
}
Button {
onClicked: {
customClass.receiveComponent(AddMyComponent.addMyComponent)
}
}
}
还有我的 C++ 类头文件:
Q_INVOKABLE void receiveComponent(const QObject& obj /* QObject ref doesn't work */);
和正文:
void CustomClass::receiveComponent(const QObject& obj) {
qDebug(obj.property("width")); // To see if we have received it correctly
}
如何将使用 JavaScript 和 Qt.createComponent
创建的组件解析为自定义 C++ 类的函数参数?
最佳答案
我们有从 QQuickItem
(对于 Qt Quick)派生的 QML UI 对象,它是 QObject
和其他也在从 QObject< 派生的 QML 中使用的“辅助”对象
基地:
// QObject pointer should work with QML objects
Q_INVOKABLE void receiveComponent(QObject* pObj);
请注意,还有 QString
、QVariant
、QVariantList
、QVariantMap
和其他 Qt 原语。对于 reference .
关于javascript - 将 JavaScript QML 项解析为 C++ QT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48637130/