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

问题描述 投票:1回答:1

这是我的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"
qt qml qt5
1个回答
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"
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.