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

如何在Qt QML TableView的单元格中按年龄阈值绘制三色圆形

核心问题原因

  1. DelegateChooser 未指定 role 属性,无法按角色匹配 DelegateChoice,对应装饰器的委托永远不会被调用
  2. 你没有在QML侧访问对应Qt::DecorationRole映射的属性,C++ model只有当QML侧请求对应角色数据时才会触发data函数的对应角色分支

修改方案

我们可以采用更简单的实现方式,无需额外使用DecorationRole,直接用已有的display角色数据完成需求,仅需要修改QML的委托部分即可:

1. 替换main.qml中TableView的delegate代码

把原来的delegate: DelegateChooser { ... }整块替换为以下代码:

delegate: Rectangle {
    anchors.fill: parent
    color: "white"

    Text {
        text: display
        anchors.left: parent.left
        anchors.leftMargin: 10
        color: 'black'
        font.pixelSize: 15
        verticalAlignment: Text.AlignVCenter
    }

    // 平均年龄列(索引为1)绘制彩色圆形
    Rectangle {
        visible: column == 1
        width: 16
        height: width
        radius: width / 2
        anchors.right: parent.right
        anchors.rightMargin: 8
        anchors.verticalCenter: parent.verticalCenter

        color: {
            const age = Number(display)
            if (age < 13) return "red"
            else if (age < 35) return "yellow"
            else return "green"
        }
    }
}

可选:坚持使用DecorationRole实现的修改步骤

如果你需要通过Qt::DecorationRole传递数据,需要做三处修改:

  1. 修改modeldata.cpp的roleNames定义,确保QML侧可以访问到对应角色:
QHash<int, QByteArray>
ModelList::
roleNames() const
{
  return {
    { Qt::DisplayRole, "display" },
    { Qt::DecorationRole, "decoration" }
  };
}
  1. 修改data函数的DecorationRole分支,返回年龄数值:
if ( role == Qt::DecorationRole && index.column() == 1 )
{
    return modelItem.averageAge;
}
  1. 在QML委托中引用decoration属性即可触发C++对应分支,颜色判断逻辑和上面的实现一致,只需要把Number(display)换成decoration即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 10:06:01