Raju
Raju

Reputation: 1169

Not able to instantiate multiple QML objects

Here is my QML file, which contains a Text component:

import QtQuick 2.0

Item {
    id: idItmWrapText
    Text {
        id: idTxtTitle
        text: qsTr("Hello World")
        font.pointSize: 20
       }
}

Now in the Test.qml file I'm instantiating the above component three times, but it is showing only once in the ouput. My Test.qml file is shown below:

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{

            }
        }
    }



}

The output is:

                     **Hello World**     //showing only once

Why is this happening?

Upvotes: 3

Views: 420

Answers (1)

TheBootroo
TheBootroo

Reputation: 7518

That's perfectly normal : In fact your component shows 3 times but overlapping one another so you think there is only one of them...

Why ?

Simply because in you component, you put the Text inside an Item but you didn't tell to the Item to be the same size as the inner Text, so it keeps 0x0 size.

But why the text is visible ?

By default Item is not clipped, which means content can be displayed even if it goes outside the border of the Item.

How to fix it ?

Simply anchor the Text correctly inside the Item and bind the Item height on the Text real height, inside your custom component :

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

And it's done !

Upvotes: 8

Related Questions