繁体   English   中英

从另一个QML文件访问TextField

[英]Accessing TextField from Another QML File

我有两个.qml文件:

CustomText.qml

Item 
{
    TextField
    {
        id: t1
        placeholderText: qsTr("Enter name")
    }
}

main.qml

Window 
{
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    CustomText {width: 200; height: 200}

    Rectangle
    {
        id: r1      
        border.color: "black"
        width: 200
        height: 200
        x: 200
        y: 200
        Text 
        {
            text: t1.text
        }
    }
}

该代码不起作用,因为该ID未知。 如何从main.qmlTextField访问文本?

有两种方法可以完成此操作,即

  1. 别名t1.text ,绑定customText.text
  2. 别名t1 ,绑定customText.t1.text

请注意,在这两种方法中,我们都需要为您的CustomText实例提供一个id ,以便我们可以引用它。 在这两种方法中,我们还将利用property aliases 这些允许您公开CustomText某些属性。

别名t1.text ,绑定customText.text

// CustomText.qml
Item 
{
    property alias text: t1.text    // set a property alias

    TextField
    {
        id: t1
        placeholderText: qsTr("Enter name")
    }
}

// Main.qml
Window 
{
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    CustomText { id: customText; width: 200; height: 200 }   // provide an id for reference    

    Rectangle
    {
        id: r1      
        border.color: "black"
        width: 200
        height: 200
        x: 200
        y: 200
        Text 
        {
            text: customText.text      // bind the text property
        }
    }
}

别名t1 ,绑定customText.t1.text

// CustomText.qml
Item 
{
    property alias t1: t1      // set a property alias

    TextField
    {
        id: t1
        placeholderText: qsTr("Enter name")
    }
}

// Main.qml
Window 
{
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    CustomText { id: customText; width: 200; height: 200 }    // provide an id for reference    

    Rectangle
    {
        id: r1      
        border.color: "black"
        width: 200
        height: 200
        x: 200
        y: 200
        Text 
        {
            text: customText.t1.text    // bind the property
        }
    }
}

如果您只需要使用TextField的文本,而没有其他选择,我建议您使用第一种方法,因为您仍然将t1的其余部分封装了起来(一个人也可能会说“ private ”变量)。

通常,除非必须在文件外部修改整个 t1对象,否则永远不要使用第二种方法。 (可能会有一些例外,但是这种模式倾向于暗示设计模式中的缺陷,需要重构。)坚持第一种方法。 如果您发现自己不得不引用/修改TextField其他属性( placeholderTextfont等),则应别名并公开这些属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM