【问题标题】:How to make ListView items height dynamic based on inner content?如何根据内部内容使 ListView 项目高度动态化?
【发布时间】:2018-09-19 09:45:42
【问题描述】:

在以下列表视图的项目中,文本的长度可以不同(10 或 1000 个字符),所以我想让每个列表视图项目的高度适合文本高度。 (如 CSS 高度:自动)。

 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)

【问题讨论】:

    标签: qt listview qml qt-quick qtquickcontrols2


    【解决方案1】:

    Text 要能够换行(或省略),需要设置宽度,否则会无限扩展。

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

    • width:将其视为文本行的最大宽度,除非您不想限制屏幕宽度(您可以水平滚动或平移),否则应始终设置它。设置 wrapModeelide 而不设置 width 将无效。
    • implicitWidth:文本需要占据的宽度以适合单行。包括左右padding。不依赖于显式的width。不确定何时使用它¯\_(ツ)_/¯ 在 cmets 中有什么想法吗?
    • 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2011-04-24
      • 2012-07-29
      • 2015-03-06
      相关资源
      最近更新 更多