簡體   English   中英

如何在QML中將QML項目分配給組件屬性,然后在組件內部使用該對象?

[英]How do you assign a QML Item to a component property in QML and then use that object inside the component?

我正在嘗試創建一個QML對象,其作用類似於其他對象的包裝器。 這是我的QML文件(Container.qml):

Item {
    property string label
    property Item control

    Row {
        Label {
            text: label
        }

        // Not sure how to display the control assigned to the control property
    }
}

我想做什么(在我的QML中使用這個組件)是這樣的:

Container {
    label: "My Label"
    control: Textbox {
        text: "My Value"
    }
}

當輸入QML時,結果(在界面中)應該類似於此QML的輸出:

Item {
    Row {
        Label {
            text: "My Label"
        }
        Textbox {
            text: "My Value"
        }
    }
}

這可能嗎? 當我嘗試這樣做時,在將一個Item分配給control屬性時,我得到“無法將對象分配給屬性”。 我搜索了Qt論壇並無情地搜索了這個,但沒有成功。 如果有人知道答案,我將不勝感激。

謝謝

插口

有更好的解決方案:

/* MyObject.qml */

Rectangle {
    default property alias data /* name can be any */ : inner_space.data

    /* ... You can put other elements here ... */
    Item {
       id: inner_space

       /* ... Params ... */
    }
    /* ... You can put other elements here ... */
}

現在我們可以做我們想要的一切!

/* main.qml */

Rectangle {
    MyObject {
        Button {
             /* ... */
        }
    }
}

感謝用戶bobbaluba建議使用data屬性而不是children

您可以使用Loader元素動態加載項目,然后將'control'屬性設置為直接引用加載器的sourceComponent屬性的別名

所以你的Container.qml看起來像這樣:

Item {
    property string label
    property alias control : loader.sourceComponent

    width: 200; height: 200

    Row {
        Label { text: label }
        Loader { id: loader }
    }
}

現在,當您將圖形項目分配給“control”屬性時,Loader將自動顯示該圖形項。

您可以使用自定義屬性為其他項創建容器:

Item
{
    id: root

    property list<Item> rectList: [
        Rectangle
        {
            parent: root
        },
        Rectangle
        {
            parent: root
        },
        Rectangle
        {
            parent: root
        },
        Rectangle
        {
            parent: root
        }
    ]
}

請注意,矩形項的父項是手動設置的,因此它們將是容器的可視子項。

您可以將它們評估為javascript數組

for ( var i = 0; i < root.rectList.length; i++ )
{
   var rect = root.rectList[i];
   rect.visible = true;
}

要么

rect.rectList[1].visible = false;

現在使用QML大約一個月了,我不知道怎么做到這一點我很害怕。

最好的計划是找出控件(示例中的Textbox )可能存在的所有可能的東西,創建行中每個組件的實例,並在Item上設置相應的狀態。 然后,州將根據需要使所需組件可見或不可見。

編輯

只是覺得。 (還沒試過,但試一試!)在你的ItemComponent.onCompleted: handler中,嘗試調用control.createObject(rowID) ,其中rowID是你的Row對象的id ,(你想成為父對象) control )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM