首页 文章

Qml:如何根据内容使listview项高度动态?

提问于
浏览
1

在下面的listview的项目中,文本的长度可以是不同的(10或1000个字符),所以我想让每个列表视图项高度适合文本高度 . (比如css height:auto) .

Component {
        id: sysNotificationsDelegate        
        Rectangle {
            anchors.left: parent.left
            anchors.right: parent.right
            height: childrenRect.height                        
            color: "#eee"        
            Text {        
                text: model.body // <-- TEXT SIZE CAN BE DIFFERENT     
                wrapMode: Text.WordWrap
            }
        }
    }


ListView {
       anchors.fill: parent            
       spacing: 10

       model: ListModel {
           id: listModel
       }
       delegate: sysNotificationsDelegate    
}

什么是适当和最高效的方法来实现这一目标? (考虑到我将有很多这样的元素,并且我已经读过qml中的属性绑定有一些额外的性能成本)

(Qt 5.10)

1 回答

  • 4

    对于 Text 能够包装(或删除),它需要设置宽度,否则它将无限制地扩展 .

    Text 有3个重要的宽度属性:

    • width :将其视为文本行的最大宽度,除非您不想限制屏幕宽度(可以水平滚动或平移),否则应始终设置它 . 设置 wrapModeelide 没有 width 将无效 .

    • implicitWidth :文本需要占据的宽度以适合单行 . 包括左右 padding . 不依赖于显式 width . 不确定何时使用它¯\ (ツ) /¯评论中的任何想法?

    • contentWidth :文本实际占用的宽度考虑到包装和删除 . 不包括左右 padding . 取决于明确的 width . 使用此选项查询文本的宽度,例如,当您想要在某些文本(例如聊天气泡)周围绘制框时 .

    高度也存在相同的相应属性 . maximumLineCount 除了显式 height 外,还可以限制文本的高度

    这意味着在你的情况下你想做:

    Rectangle {
        anchors.left: parent.left
        anchors.right: parent.right
        height: text.contentHeight // contentHeight, height and implicitHeight are all the same here since there's no padding, no maximumLineCount and height isn't explicitely set                        
        color: "#eee"        
        Text {
            id: text
            text: model.body // <-- TEXT SIZE CAN BE DIFFERENT
            width: parent.width // remember, width = max width for Text
            wrapMode: Text.WordWrap
        }
    }
    

相关问题