QMLQt

QML动态创建C++对象

2016-08-24  本文已影响93人  丰宁

参考:

目前发现有两种方法,第一种方法是使用property var,第二种方法是使用脚本。两种方法各有优缺点:

本文还提到了一种使用qml文件包裹c++自定义类型的方法,见参考链接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;
上一篇下一篇

猜你喜欢

热点阅读