如何在其他qml文件中设置'Text'QML Component的文本属性?

时间:2017-12-12 05:12:16

标签: qt qml qt5

这是我的Box.qml
我想将此Box用作自定义QML组件。

 import QtQuick 2.5
      Rectangle{
            id: sample
            width: 100
            height: 35
            border.color: "Black"
            color: "#778899"
            Text{
                font.pointSize: 10
                font.bold: true
                anchors.centerIn: parent
           }
      }

这是我的main.qml

 import QtQuick 2.5
 import QtQuick.Window 2.2
 Window {
   visible: true
   width: 640
   height: 480
   title: qsTr("Repeater")
   Box{
       text: "Number"
   }
}

但这不起作用 我收到了以下错误

qrc:/main.qml:11 Cannot assign to non-existent property "text"

1 个答案:

答案 0 :(得分:3)

您必须通过property公开该属性。

<强> Box.qml

import QtQuick 2.5
Rectangle{
    property string mytext
    id: sample
    width: 100
    height: 35
    border.color: "Black"
    color: "#778899"
    Text {
        font.pointSize: 10
        font.bold: true
        anchors.centerIn: parent
        text: mytext
    }
}

<强> main.qml

import QtQuick 2.5
import QtQuick.Window 2.2
Window {
   visible: true
   width: 640
   height: 480
   title: qsTr("Repeater")
   Box{
       mytext: "Number"
   }
}

或使用alias

<强> Box.qml

import QtQuick 2.5
Rectangle{
    property alias text: txt.text
    id: sample
    width: 100
    height: 35
    border.color: "Black"
    color: "#778899"
    Text {
        id: txt
        font.pointSize: 10
        font.bold: true
        anchors.centerIn: parent
    }
}

<强> main.qml

import QtQuick 2.5
import QtQuick.Window 2.2
Window {
   visible: true
   width: 640
   height: 480
   title: qsTr("Repeater")
   Box{
       text: "Number"
   }
}