如何内联定义QML组件并覆盖属性?

Ste*_*ows 0 qml qqmlcomponent

我正在尝试一些看似简单的事情,但失败了:内联定义一个简单的文本格式设置组件,然后使用不同的文本多次实例化它。这是代码

Item {
.
.
.
Component {
    id: favButtonLabelText
    Text {
        text: "Blah!"
        color: StyleSingleton.xNavPrimaryText
        font.family: StyleSingleton.xNavTextFont
        font.pointSize: 28
    }
}
.
.
.       
Loader { sourceComponent: favButtonLabelText; text: "Diameter" }
Run Code Online (Sandbox Code Playgroud)

在加载程序行,text属性无效。试图在组件上定义属性或别名的尝试被拒绝,“组件对象无法声明新属性”。

我在文档中找到的唯一示例显示了重写内联组件中定义的x属性Rectangle。在我看来,覆盖元素的text属性Text是类似的。

我怎样才能做到这一点?

ska*_*esh 9

从 Qt 5.15 开始,添加了一个新功能:内联组件

顾名思义,它允许定义内联组件,具有以下优点:

您可以创建组件的实例,而无需使用加载程序的开销。
您可以在属性声明中使用组件类型。
您可以在定义该组件之外的其他文件中引用该组件。

Item {
.
.
.
component FavButtonLabelText: Text {
     property int aCustomProp: 0

     text: "Blah!"
     color: StyleSingleton.xNavPrimaryText
     font.family: StyleSingleton.xNavTextFont
     font.pointSize: 28
}
.
.
.      
FavButtonLabelText { text: "myNewText"; aCustomProp: 5 }
Run Code Online (Sandbox Code Playgroud)


Gre*_*cKo 5

由于Loader将自身设置为要加载的组件的上下文对象,因此您可以在其中定义一个属性,然后在loaded中使用它Item
但是,您必须使用项目未使用的属性名称,否则它将被项目自身的属性遮盖,并且没有简单的方法可以显式访问上下文属性。

Component {
    id: favButtonLabelText
    Text {
        text: foobar
    }
}
Loader {
    sourceComponent: favButtonLabelText
    property string foobar: "Diameter"
}
Run Code Online (Sandbox Code Playgroud)


der*_*erM 5

正如GrecKo已经说过的那样,可以使用Loader具有另一个名称的的自定义属性,例如在他的示例中foobar

如果您不对加载的Item内容进行任何华丽的重造,也可以使用相同的名称,并使用parent.property

Component {
    id: textComponent
    Text {
        // Use "parent" to reference the property of the parent,
        // which is by default the Loader
        text: parent.text
    }
}

Column {
    Repeater {
        model: ['hallo welt', 'hello world', 'Bonjour monde', '????']
        delegate: Loader {
            property string text: modelData
            sourceComponent: textComponent
        }
    }
}
Run Code Online (Sandbox Code Playgroud)