QML动态创建自定义组件


1、创建新的QML,注意文件第一个字母要大写

ZStation.qml

import QtQuick 2.5

Rectangle{
    property string mName: "station"
    signal entered(string objName);
    signal exited();
    property int station_width: width/3

    id: root
    color: Qt.rgba(0,0,0,0)
    width: 90
    height: width/3
    Rectangle{
        id: station
        color:"green"
        width: station_width
        height: width
        radius: width/2
    }
    Text {
        anchors.top:parent.top;
        anchors.left: station.right;
        anchors.leftMargin: 5;
        width: 30
        height: 12
        text: mName
        color: "white"
    }
    MouseArea {
        hoverEnabled: true;
        anchors.fill: parent;
        onEntered: {
            root.entered(root.objectName);
        }
        onExited: {
            root.exited();
        }
    }
}

2、在主qml里动态创建并连接信号槽

function addStation(x, y, id, name){
    console.log(x,y,id,name);
    var componentIn = Qt.createComponent("ZStation.qml");
    if (componentIn.status === Component.Ready) {
        var objIn = componentIn.createObject(root, {"mName":name, "objectName":id});
        if(auto_scale){
            x = getNearX(x);
            y = getNearY(y);
        }

        objIn.x = x;
        objIn.y = y;
        objIn.entered.connect(root.showPopInfo)
        objIn.exited.connect(root.hidePopInfo)
        station_list.push(objIn);
        console.log(x,y);
    }else{
        console.log("qml create station err:",componentIn.errorString());
    }
}
QML