QML動(dòng)態(tài)創(chuàng)建C++對象

參考:

目前發(fā)現(xiàn)有兩種方法,第一種方法是使用property var,第二種方法是使用腳本。兩種方法各有優(yōu)缺點(diǎn):

  • 使用property var,不需要外掛腳本,代碼簡單清晰,但是會對外暴露不必要的屬性
  • 使用腳本優(yōu)缺點(diǎn)恰恰與第一種方法相反

本文還提到了一種使用qml文件包裹c(diǎn)++自定義類型的方法,見參考鏈接2。

不多說,直接上代碼:

MyCustomObj.h

#ifndef MYCUSTOMOBJ_H
#define MYCUSTOMOBJ_H

#include <QObject>

class MyCustomObj : public QObject
{
    Q_OBJECT
public:
    explicit MyCustomObj(QObject *parent = 0);

    Q_INVOKABLE void func();
};

#endif // MYCUSTOMOBJ_H

MyCustomObj.cpp

#include "MyCustomObj.h"

#include <QDebug>

MyCustomObj::MyCustomObj(QObject *parent) : QObject(parent)
{

}

void MyCustomObj::func()
{
    qDebug("Fun with QML");
}

main.qml

import QtQuick 2.7
import QtQuick.Window 2.2

import com.myProject.myCustomStuff 1.0

import "MyObj.js" as MyJsObj

Window {
    id: mainWindow
    visible: true
    width: 640
    height: 480
    title: qsTr("qml-dynamic-create-cpp-object")
    property var my_obj;

    Component {
        id: myComponent

        MyCustomObj {

        }
    }

    Component.onCompleted: {
        my_obj = myComponent.createObject(mainWindow)
        if (!my_obj) console.error("Error creating object")

        console.log(typeof(my_obj))
        console.log(Qt.isQtObject(my_obj))

        my_obj.func()

        MyJsObj.my_js_obj = myComponent.createObject(mainWindow);
        if (!MyJsObj.my_js_obj) console.error("Error creating object")
        console.log(typeof(MyJsObj.my_js_obj))
        console.log(Qt.isQtObject(MyJsObj.my_js_obj))

        MyJsObj.my_js_obj.func();

        var componentWrapper = Qt.createComponent("MyCustomObjWrapper.qml")
        var obj = componentWrapper.createObject(mainWindow);

        console.log(typeof(obj))
        console.log(Qt.isQtObject(obj))
        obj.func();
    }

    MainForm {
        anchors.fill: parent
        mouseArea.onClicked: {
            Qt.quit();
            my_obj.func();
            MyJsObj.my_js_obj.func();
        }
    }
}

MainForm.ui.qml

import QtQuick 2.7

Rectangle {
    property alias mouseArea: mouseArea

    width: 360
    height: 360

    MouseArea {
        id: mouseArea
        anchors.fill: parent
    }

    Text {
        anchors.centerIn: parent
        text: "Hello World"
    }
}

MyCustomObjWrapper.qml

import QtQuick 2.0

import com.myProject.myCustomStuff 1.0

MyCustomObj {
    id: obj
    Component.onCompleted: {
        console.log("Created from QML dynamically ")
        obj.func()
    }
}

MyObj.js

var my_js_obj = null;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容