You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt 5.9 ListView仅显示一个ListItem问题求助

Qt ListView分组仅显示第一个列表项问题排查与解决

问题描述

我正尝试复刻Qt 5.9官方的ListView分组示例,预期按动物尺寸分组显示所有列表项,每个分组对应标题;但实际运行后,所有分组标题正常显示,仅“Parrot”这一个列表项被展示。使用环境为Qt 5.9 + Ubuntu 18.04。

预期效果:
预期视图

实际效果:
实际视图

问题代码

import QtQuick 2.0

Item {
        anchors.fill: parent

    Component {
        id: sectionHeading
        Rectangle {
            width: parent.width
            height: childrenRect.height
            color: "lightsteelblue"
       
            Text {
                text: section
                font.bold: true
                font.pixelSize: 20
            }
        }
    }

    ListModel {
        id: animalsModel
        ListElement {
            size: "Small"
            name: "Parrot"
        }
        ListElement {
            size: "Small"
            name: "Guinea pig"
        }
        ListElement {
            size: "Medium"
            name: "Cat"
        }
        ListElement {
            size: "Medium"
            name: "Dog"
        }
        ListElement {
            size: "Large"
            name: "Elephant"
        }
    }

    ListView {
        id: view
        anchors.top: parent.top
        width: parent.width
        model: animalsModel
        delegate: Text {
            text: name
            font.pixelSize: 18
        }
        section.property: "size"
        section.criteria: ViewSection.FullString
        section.delegate: sectionHeading
    }
}

原因分析

问题核心是ListView未设置有效高度约束:仅通过anchors.top: parent.top指定了顶部位置,但未定义底部边界或高度值,导致ListView默认高度仅能容纳第一个列表项和对应的分组标题,后续内容被容器裁剪无法显示。

修复方案

提供两种可行的修复方式:

方式一:锚定父组件上下边界

让ListView填充父组件的垂直空间,添加anchors.bottom: parent.bottom属性:

ListView {
    id: view
    anchors.top: parent.top
    anchors.bottom: parent.bottom
    width: parent.width
    model: animalsModel
    delegate: Text {
        text: name
        font.pixelSize: 18
    }
    section.property: "size"
    section.criteria: ViewSection.FullString
    section.delegate: sectionHeading
}

方式二:直接设置高度值

将ListView高度设为父组件高度,或者根据需求设置固定高度:

ListView {
    id: view
    anchors.top: parent.top
    width: parent.width
    height: parent.height
    model: animalsModel
    delegate: Text {
        text: name
        font.pixelSize: 18
    }
    section.property: "size"
    section.criteria: ViewSection.FullString
    section.delegate: sectionHeading
}

修复后,ListView会拥有足够的垂直空间展示所有分组和列表项,超出空间的内容会自动激活滚动功能。

内容的提问来源于stack exchange,提问作者Stephen Rasku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:03:39