2013-08-06 38 views
3

這裏是我的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 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 

這究竟是爲什麼?

回答

8

這是完全正常的:其實你的組件顯示3次,但彼此重疊,所以你覺得只有其中之一...

爲什麼?

只是因爲在你的組件中,你把文本放在一個Item中,但是你沒有告訴Item與內部Text有相同的大小,所以它保持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; 
     } 
    } 
} 

它完成!