我在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 ++类'功能参数?
答案 0 :(得分:3)
我们有QML UI对象派生自QQuickItem
(对于Qt Quick),QObject
和其他辅助' QML中使用的对象也来自QObject
base:
// QObject pointer should work with QML objects
Q_INVOKABLE void receiveComponent(QObject* pObj);
请注意,还有QString
,QVariant
,QVariantList
,QVariantMap
和其他Qt原语。对于reference。