将JavaScript QML项解析为C ++ QT

时间:2018-02-06 06:57:37

标签: javascript c++ qt

我在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 ++类'功能参数?

1 个答案:

答案 0 :(得分:3)

我们有QML UI对象派生自QQuickItem(对于Qt Quick),QObject和其他辅助' QML中使用的对象也来自QObject base:

// QObject pointer should work with QML objects
Q_INVOKABLE void receiveComponent(QObject* pObj);

请注意,还有QStringQVariantQVariantListQVariantMap和其他Qt原语。对于reference