2017-07-31 88 views
0

所以我有一個內部帶有標籤文本的矩形。如果文本太長而無法放入一行,我想增加矩形的大小,否則應該保持不變。根據是否包裝文字來調整矩形大小QML

到目前爲止,我嘗試使用lineCount,剪輯,截斷特性從 qt的docs -

的文本不適合,我也得到橢圓。但是,剪輯和截斷總是返回false。線數只是返回當前的線數,忽略它應該佔用更多空間。

現在我試圖從here使用contentWidth。但是,這總是返回一個等於或小於實際寬度的值。我認爲這應該返回它應該佔據的總價值?

我該如何做到這一點?

編輯

我想這樣的事情,但是不管我的文字是多久或多截斷它是內容的寬度總是比標籤的寬度。我從qml文檔中得到了contentWidth即使忽略文本也會考慮到的印象。

Rectangle{ 
    id: rec 
    ... 
    Label{ 
    id: messageText 
    height: Format.singleLine 
    text: "this text is very long and should be two lines" 
    Component.onCompleted: { 
     if (contentWidth > width){ 
     rec.height = Format.multipleLines 
     } 
    } 
    } 
} 

第二個編輯

我才知道,爲什麼lineCount總是一個原因是由於編程創建對象(myRectangle是包含標籤的矩形):

messages.source = Qt.resolvedUrl("myRectangle.qml"); 
    messages.item.message = message; 

後標籤創建的第一行label使用lineCount 1。然後我會嘗試更改僅在此點之後被截斷的文本。

+0

顯示您的代碼請 – eyllanesc

+0

我只是想能夠這樣做: 寬度:(contentWidth>寬度)? Format.multipleLines:Format.singleLine; –

+0

我認爲你已經有足夠的聲望知道你必須提供[最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve)。除此之外,你應該知道如何[編輯](https://stackoverflow.com/posts/45425718/edit)你的問題。 – eyllanesc

回答

1

怎麼是這樣的:

height: lineCount > 1 ? Format.multipleLines : Format.singleLine 
+0

這並沒有起作用,因爲lineCount會根據當前高度而有所不同。我最終將標籤高度初始化爲多行,然後如果只有一行,則將高度更改爲singleLine。 –

0

如果矩形只包含你的標籤,你可以做這樣的事情依賴於標籤的wrapMode屬性和矩形的childrenRect.height財產。

Rectangle { 
    anchors.centerIn: parent 
    width: 200 
    height: childrenRect.height 
    border.width: 1 

    Label { 
     id: messageText 
     width: 200 
     wrapMode: Text.Wrap 
     text: "This text is very long very long. Like way too long to fit on a single line." 
    } 
} 

另外,如果你不介意你的標籤包含矩形的,而不是周圍的其他方法,你可以這樣做:

Label { 
    id: messageText 
    anchors.centerIn: parent 
    width: 200 
    wrapMode: Text.Wrap 
    text: "This text is very long very long. Like waaaaay too long to fit on a single line." 

    Rectangle { 
     anchors.fill: parent 
     z: -1 
     border.width: 1 
    } 
} 
0

我不知道是否有更好的辦法要做到這一點,但此代碼爲我做了(這是在標籤內):

onContentWidthChanged: { 
     if((lineCount === 1) && (contentWidth !== 0)){ 
      rec.height = Format.singleLine; 
     } 
     else{ 
      rec.height = Format.multipleLines; 
     } 
    } 

我初始化高度爲Format.multipleLines。然後,一旦文本被說明(ContentWidth不是0),我檢查lineCount是否是1。如果是這樣,我將高度修改爲format.singleLine。

請注意,在創建組件後,onContentWidth會調用兩次。首次contentWidth將始終爲0(因此需要檢查它)。