Qt6中如何为QAbstractTableModel关联的柱状图图例设置自定义标签
解决QML柱状图图例标签显示列索引的问题
原因分析
VBarModelMapper默认会将列索引作为对应的BarSet名称(即图例显示的文本),这和roleNames无关——roleNames主要用于QML视图按角色访问数据,并不控制图表图例的标签。
解决方案
在Component.onCompleted中遍历barSeries的barSets,手动为每个BarSet设置自定义的name属性即可。
修改后的main.qml代码
Item{ Layout.fillHeight: true Layout.fillWidth: true Layout.columnSpan: 2 ChartView { anchors.fill: parent theme: ChartView.ChartThemeDark antialiasing: true legend.visible: true title: "Loans" CategoryAxis { id: axisX labelsPosition: CategoryAxis.AxisLabelsPositionOnValue titleText: "Borrower" } ValueAxis { id: axisY min: 0 max: 10000 tickCount: 5 titleText: "Total Loan" } BarSeries { id: barSeries axisX: axisX axisY: axisY } VBarModelMapper { id: modelMapper firstBarSetColumn: 2 lastBarSetColumn: 3 firstRow: 0 model: ParticipantModel rowCount: ParticipantModel.rowCount() series: barSeries } Component.onCompleted: { // 填充X轴分类 for (var i = 0; i < ParticipantModel.rowCount(); ++i) { axisX.append(ParticipantModel.data(ParticipantModel.index(i,1), ParticipantModel.NameRole), i); } // 设置图例自定义标签 if (barSeries.barSets.length > 0) { barSeries.barSets[0].name = "Loans"; barSeries.barSets[1].name = "Lendings"; } } } }
进阶动态获取标签(可选)
如果需要从模型中动态获取标签(比如表头数据),可以重写模型的headerData方法:
1. 在ParticipantModel头文件中声明方法
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
2. 在ParticipantModel.cpp中实现方法
QVariant ParticipantModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch(section) { case 2: return "Loans"; case 3: return "Lendings"; default: return QAbstractTableModel::headerData(section, orientation, role); } } return QAbstractTableModel::headerData(section, orientation, role); }
3. 在QML中调用获取标签
Component.onCompleted: { // ... 其他代码 // 从模型表头动态获取标签 if (barSeries.barSets.length > 0) { barSeries.barSets[0].name = ParticipantModel.headerData(2, Qt.Horizontal); barSeries.barSets[1].name = ParticipantModel.headerData(3, Qt.Horizontal); } }
内容的提问来源于stack exchange,提问作者aasdag
相关产品推荐
相关产品推荐

