无法实例化多个QML对象

时间:2013-08-06 12:44:48

标签: qml

这是我的QML文件,其中包含Text组件:

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

为什么会这样?

1 个答案:

答案 0 :(得分:8)

这是完全正常的:实际上你的组件显示3次但彼此重叠,所以你认为只有其中一个......

为什么?

只是因为在你的组件中,你将Text放在一个Item中,但你没有告诉Item与内部Text的大小相同,所以它保持0x0大小。

但为什么文字可见?

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

如何解决?

只需将Text正确锚定在Item中,并将Item高度绑定在Text自定义组件内的Text实际高度上:

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;
        }
    }
}

已经完成了!