如何在QML QT5中显示分配的属性组件?

How to display the assigned property component in QML QT5?

在Main.qml

Item {
    id:windowId
    width:200;height;200;
    Page{
      style: MyStyle{
           id:myStyleId
           background: Rectangle{
                width:30;height;30;color:"blue"
           }  
           background2: Rectangle{
                width:10;height;10;color:"green"
           }             
      }
    }
}

在Page.qml

Item {
    id: pageId
    property MyStyle style
    //How to display the style property
}

在MyStyle.qml

 Item {
    id: mystyleId
    property Rectangle background
    property Rectangle background2
    //How to display the background and background2 properties
 }

正如您在上面看到的,我在创建 Page

时使用 MyStyle 分配了样式 属性

如何在页面中显示样式 属性,在 MyStyle 中显示背景 属性。

我在 Page.qml 中尝试过这样做,在 MyStyle.qml 中也尝试过这样做,但仍然没有显示,没有任何错误

Item {
    property alias style : loader.sourceComponent

    Loader { id: loader }
}

最后一张草图:(1)Page.qml; (2,3) 来自 Style.qml

的矩形

分配给 属性 的项目不会得到它们的 parent 集合。

当你有想法时:

ItemA {
    ItemB {}
}

ItemB 将自动设置为 ItemA.children 的一部分,而 ItemB.parent 将设置为 ItemA

这不会发生,如果你写:

ItemA {
    property Item someItem: ItemB {}
}

此处将ItemB.parent设为nullItemB不会出现在ItemA.children中。


这意味着,您需要手动设置它,方法是将其添加到所需的 parents children-属性,或设置 parent- 属性 的 child.

ItemA {
    id: itmA
    property Item someItem: ItemB { parent: itmA }
}

使ItemB出现


因为,很可能,你不想每次在那个 属性 中放东西时都写那个,你可以使用 onPropertyChanged-slot 来做到这一点:

ItemA {
    property Item someItem
    onSomeItemChanged: someItem.parent = this
}

在这种情况下,当您将新的 Item 分配给 someItem 时,前一个不会丢失 parent,并且仍会绘制在同一位置。因此,您可能还想创建一个连接以再次删除 parent。 为此,我们将创建一个闭包来存储连接的引用:

Item {
    id: root
    property Item someItem
    onSomeItemChanged: {
        console.log('SomeItem changed')
        someItem.parent = root
        this.onSomeItemChanged.connect(generateClosure(someItem))
    }

    function generateClosure(smeItm) {
        return function() { if (someItem !== smeItm) { smeItm.parent = null } }
    }
}

或者如果你想恢复原来的parent我们使用这个函数来关闭:

function generateClosure(smeItm, originalParent) {
    return function() { if (someItem !== smeItm) { smeItm.parent = originalParent } }
}

并确保,只要我们仍然有对原始 parent 的引用,我们就会调用它。