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

QML ListView未显示绑定模型数据:仅展示静态项求助

解决QML ListView无法显示模型数据的问题

问题概述

登录页面需展示用户列表,已基于QAbstractListModel创建UserListModel并填充2个用户,但QML页面中仅静态ListItem显示,绑定模型的用户条目未出现,需优先解决数据显示问题。

核心问题排查与修复方案

1. 确保模型角色名称匹配

在UserListModel的roleNames()函数中,必须明确返回与QML绑定对应的角色名称。因为QML中delegate绑定的是name,所以C++模型里要定义该角色:

QHash<int, QByteArray> UserListModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[NameRole] = "name"; // NameRole需定义为Qt::UserRole + 1之类的自定义角色
    return roles;
}

同时,data()函数要正确返回对应角色的数据:

QVariant UserListModel::data(const QModelIndex &index, int role) const {
    if (!index.isValid()) return QVariant();
    const User &user = m_users[index.row()];
    if (role == NameRole) {
        return user.name();
    }
    return QVariant();
}

2. 修复ListView的布局空间问题

当前RowLayout中的ListView未设置布局属性,导致没有分配到显示空间,所以看不见。修改logon.qml中的ListView:

ListView {
    model: user.model
    clip: true
    // 添加布局属性,让ListView在RowLayout中获取足够空间
    Layout.fillWidth: true
    Layout.fillHeight: true
    delegate: ListItem { text1: name; text2: ""}
}

3. 验证模型实例的上下文注册

确保C++端已将UserListModel实例正确注册到QML上下文,比如:

UserListModel *userModel = new UserListModel(this);
// 填充用户数据...
engine.rootContext()->setContextProperty("user", userModel);
// 或者如果是user.model的结构,要确保对应的属性正确指向模型实例

修改后的关键代码示例

logon.qml(修复布局后的版本)

Rectangle {
    id: userlist
    Layout.fillWidth: true
    Layout.fillHeight: true
    Layout.preferredHeight: 300
    Layout.preferredWidth: 560  
    color: "white"
    RowLayout {
        ListItem { text1: "Benutzeranmeldung"; text2: "[1/2]"; icon: "key" }

        ListView {
            model: user.model
            clip: true
            Layout.fillWidth: true
            Layout.fillHeight: true
            delegate: ListItem { text1: name; text2: ""}
        }
    }
}

ListItem.qml(无需修改,保持原结构)

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Exakt.Mills.System.ColorEnums 1.0

Item {
    id: item
    height: 30
    width: 400
    property string text1
    property string text2
    property string icon

    Rectangle {
        anchors.fill: parent
        Layout.fillWidth: true
        Layout.fillHeight: true
        color : "grey"
        RowLayout {
            Image {
                sourceSize.height: item.height * 0.8
                source: "image://iconprovider/user"
            }
            Label {
                text: text1
            }
            Label {
                text: text2
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:20:26