从自定义标签访问 QML 嵌套变量成员
Access QML nested variable member from custom Label
我有以下习惯Label
:
import QtQuick 2.3
import QtQuick.Controls 1.4
Label
{
anchors.centerIn: parent
text: "DashboardLabel!"
font.pixelSize: 22
font.italic: true
color: "steelblue"
Rectangle
{
id: rectangle
}
}
我正在尝试通过访问来自 rectangle
:
的 x 和 y 变量来更改标签的位置
import QtQuick 2.3
import QtQuick.Controls 1.4
import CustomGraphics 1.0
Item
{
anchors.centerIn: parent
CustomLabel
{
id: customLabel
width: 100
height: 100
rectangle.x: 200
}
}
它似乎没有用,因为我的自定义 Label
没有被移动。我应该使用 property
功能吗?这是我收到的错误:
Cannot assign to non-existent property "rectangle"
编辑:我刚刚尝试添加 property alias rect: rectangle
以便使用 rect.x
访问 x
。我没有收到任何错误,但 window.
上什么也没有出现
你不能那样访问子元素的私有属性。您必须创建 alias
才能让子类访问它们。试试这个
import QtQuick 2.3
import QtQuick.Controls 1.4
Label
{
property alias childRect: rectangle
anchors.centerIn: parent
text: "DashboardLabel!"
font.pixelSize: 22
font.italic: true
color: "steelblue"
Rectangle
{
id: rectangle
width: 100
height: 100
}
}
然后
import QtQuick 2.3
import QtQuick.Controls 1.4
import CustomGraphics 1.0
Item
{
anchors.centerIn: parent
CustomLabel
{
id: customLabel
width: 100
height: 100
childRec.x: 200
}
}
更新 因为 OP 更改了描述
您还没有为矩形设置 width
和 height
属性。查看我的编辑。
我有以下习惯Label
:
import QtQuick 2.3
import QtQuick.Controls 1.4
Label
{
anchors.centerIn: parent
text: "DashboardLabel!"
font.pixelSize: 22
font.italic: true
color: "steelblue"
Rectangle
{
id: rectangle
}
}
我正在尝试通过访问来自 rectangle
:
import QtQuick 2.3
import QtQuick.Controls 1.4
import CustomGraphics 1.0
Item
{
anchors.centerIn: parent
CustomLabel
{
id: customLabel
width: 100
height: 100
rectangle.x: 200
}
}
它似乎没有用,因为我的自定义 Label
没有被移动。我应该使用 property
功能吗?这是我收到的错误:
Cannot assign to non-existent property "rectangle"
编辑:我刚刚尝试添加 property alias rect: rectangle
以便使用 rect.x
访问 x
。我没有收到任何错误,但 window.
你不能那样访问子元素的私有属性。您必须创建 alias
才能让子类访问它们。试试这个
import QtQuick 2.3
import QtQuick.Controls 1.4
Label
{
property alias childRect: rectangle
anchors.centerIn: parent
text: "DashboardLabel!"
font.pixelSize: 22
font.italic: true
color: "steelblue"
Rectangle
{
id: rectangle
width: 100
height: 100
}
}
然后
import QtQuick 2.3
import QtQuick.Controls 1.4
import CustomGraphics 1.0
Item
{
anchors.centerIn: parent
CustomLabel
{
id: customLabel
width: 100
height: 100
childRec.x: 200
}
}
更新 因为 OP 更改了描述
您还没有为矩形设置 width
和 height
属性。查看我的编辑。