无法实例化多个QML对象

无法实例化多个QML对象,qml,Qml,这是我的QML文件,其中包含一个文本组件: import QtQuick 2.0 Item { id: idItmWrapText Text { id: idTxtTitle text: qsTr("Hello World") font.pointSize: 20 } } 现在在Test.qml文件中,我实例化了上述组件三次,但在输出中只显示了一次。我的Test.qml文件如下所示: import QtQuick

这是我的QML文件,其中包含一个文本组件:

import QtQuick 2.0

Item {
    id: idItmWrapText
    Text {
        id: idTxtTitle
        text: qsTr("Hello World")
        font.pointSize: 20
       }
}
现在在
Test.qml
文件中,我实例化了上述组件三次,但在输出中只显示了一次。我的
Test.qml
文件如下所示:

import QtQuick 2.0

Item {
    id: idItmWrapRect
    width: 400
    height: 400
    Rectangle{
        id: idRectDisplay

        width: parent.width
        height: parent.height

        Column {
            id: idClmnLayout
            spacing: 50
            x: 195
            y: 200

           MyText{

            }
            MyText{

            }
            MyText{

            }
        }
    }



}
输出为:

                     **Hello World**     //showing only once

为什么会发生这种情况?

这很正常:事实上,您的组件显示了3次,但彼此重叠,所以您认为只有一个组件

为什么?

只是因为在组件中,您将文本放在一个项中,但您没有告诉该项与内部文本的大小相同,所以它保持0x0大小

但是为什么文本是可见的呢

默认情况下,项目不会被剪裁,这意味着即使内容超出项目边界,也可以显示内容

如何修复它

只需将文本正确定位在项目内,并将项目高度绑定到自定义组件内的文本真实高度:

import QtQuick 2.0

Item {
    id: itmWrapText;
    width: 400; // default width of the component
    height: txtTitle.contentHeight; // bind height on Text content size

    property alias title : txtTitle.text; // btw, expose property to be able to set text

    Text {
        id: txtTitle;
        text: qsTr ("Hello World");
        font.pointSize: 20;
        wrapMode: Text.WrapAtWordBoundaryOrAnywhere; // wrap content if necessary
        anchors { // force Text to stay in parent Item
            top: parent.top;
            left: parent.left;
            right: parent.right;
        }
    }
}
完成了