【问题标题】:QML ListView place new list item below last list itemQML ListView 将新列表项放在最后一个列表项下方
【发布时间】:2016-06-05 19:11:21
【问题描述】:

我正在尝试创建一个简单的聊天气泡布局,其中每个消息矩形的高度可以是可变的,而宽度是固定的。现在我们需要将新消息放在列表视图中最后一条消息的正下方。由于高度是可变的,ListView.spacing 不能在任何两个元素之间决定。那么我该如何实现呢?

列表视图代码:

    ListView{
    id: listView
    anchors.fill: parent
    anchors.top: parent.top
    anchors.topMargin: 10
    delegate: ChatMessageItem{}
    model: listModel
    spacing: 10
}

ChatMessageItem 的代码

Item{
Rectangle {
color: "#6BB9F0"
height: 50
width: (childrenRect.width < 200? childrenRect.width : 200)
radius: 7
Text {
    id: name
    text: username
}
Text {
    id: message
    text: msg
    anchors.top: name.bottom
    wrapMode: Text.WordWrap
    Component.onCompleted: {
        if(width > 200)
            width = 200;
        else if(width < 50)
            width = 50;
    }
}
}
}

【问题讨论】:

  • 什么是listModel?
  • @JeffreyvandeGlind ListModel 是类模型的派生类。模型用于将数据与视图绑定。
  • 好的,当你插入新消息时,它们是索引0 还是索引count()-1
  • 后一个选项@JeffreyvandeGlind
  • 好的,ListView 通常应该更新(如果信号被正确实现)并将最后一条消息放在底部。那么您的问题在哪里?

标签: qt qml


【解决方案1】:

您的问题是您的Item 没有高度。因此,您的ListView 不知道您的代表的身高。这与您的ListView.spacing 无关。尝试以下更改:

Item{
    height: rect.height
Rectangle {
    id: rect

color: "#6BB9F0"
height: name.paintedHeight + message.paintedHeight
width: (childrenRect.width < 200 ? childrenRect.width : 200)
radius: 7
Text {
    id: name
    text: username
}
Text {
    id: message
    text: msg
    anchors.top: name.bottom
    wrapMode: Text.WordWrap
    Component.onCompleted: {
        if(width > 200)
            width = 200;
        else if(width < 50)
            width = 50;
    }
}
}
}

【讨论】:

  • 非常感谢!
  • 这里甚至不需要外部的Item,您可以将Rectangle作为根项。
猜你喜欢
  • 2022-12-01
  • 2022-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 2010-12-19
  • 2013-09-18
相关资源
最近更新 更多