HelloGraphs
在Qt Quick 应用程序中使用 2D 图形。
HelloGraphs演示了如何制作简单的二维条形图和折线图。
下文将介绍如何使用BarSeries 创建条形图,使用LineSeries 创建折线图。
运行示例
运行示例 Qt Creator,打开Welcome 模式,然后从Examples 中选择示例。更多信息,请参阅Qt Creator: 教程:构建并运行。
条形图
示例中的第一个图形是条形图。创建时,首先创建GraphsView 组件,设置X axis 、Y axis 和theme 。X 轴是一个有 3 个类别的BarCategoryAxis 。垂直网格和轴线都是隐藏的。Y 轴是一个ValueAxis ,可见范围在 20 到 100 之间。使用tickInterval ,每 10 个数值就会显示带标签的主要刻度线。小刻度线将通过subTickCount 9
显示在每 1 个数值上,这意味着每个大刻度线之间有 9 个小刻度线。最后,theme 被添加到一个适合深色背景的主题中。该主题可调整图表背景网格、轴线和标签。
GraphsView { anchors.fill: parent anchors.margins: 16 axisX: BarCategoryAxis { categories: [2024, 2025, 2026] gridVisible: false subGridVisible: false } axisY: ValueAxis { min: 20 max: 100 tickInterval: 10 subTickCount: 9 } theme: GraphsTheme { colorScheme: GraphsTheme.ColorScheme.Dark theme: GraphsTheme.Theme.QtGreen } ...
要使其成为条形图,请添加BarSeries 。
BarSeries { ...
然后使用BarSet 将数据添加到BarSeries 中。有 3 个条形图具有自定义条形图颜色和边框属性。这些属性将覆盖GraphsTheme 可能设置的seriesColors 。
BarSet { values: [82, 50, 75] borderWidth: 2 color: "#373F26" borderColor: "#DBEB00" }
线形图
示例中的第二个图形是折线图。它也是从定义GraphsView 元素开始的。创建自定义GraphsTheme 是为了获得自定义外观。GraphsTheme 为背景网格和坐标轴提供了相当广泛的自定义可能性,它们将在theme 之后应用。
GraphsView 定义了适合该图表的axisX 和axisY 。
GraphsView { anchors.fill: parent anchors.margins: 16 theme: GraphsTheme { readonly property color c1: "#DBEB00" readonly property color c2: "#373F26" readonly property color c3: Qt.lighter(c2, 1.5) colorScheme: GraphsTheme.ColorScheme.Dark seriesColors: ["#2CDE85", "#DBEB00"] grid.mainColor: c3 grid.subColor: c2 axisX.mainColor: c3 axisY.mainColor: c3 axisX.subColor: c2 axisY.subColor: c2 axisX.labelTextColor: c1 axisY.labelTextColor: c1 } axisX: ValueAxis { max: 5 tickInterval: 1 subTickCount: 9 labelDecimals: 1 } axisY: ValueAxis { max: 10 tickInterval: 1 subTickCount: 4 labelDecimals: 1 } ...
自定义Delegate
组件用于可视化数据点。
component Marker : Rectangle { width: 16 height: 16 color: "#ffffff" radius: width * 0.5 border.width: 4 border.color: "#000000" }
要使其成为折线图,请添加LineSeries 。这将使pointDelegate 使用之前创建的自定义Delegate
组件。数据点使用XYPoint 元素添加。
LineSeries { id: lineSeries1 width: 4 pointDelegate: Marker { } XYPoint { x: 0; y: 0 } XYPoint { x: 1; y: 2.1 } XYPoint { x: 2; y: 3.3 } XYPoint { x: 3; y: 2.1 } XYPoint { x: 4; y: 4.9 } XYPoint { x: 5; y: 3.0 } }
第二个折线图系列与第一个类似。由于这是GraphsView 中的第二个LineSeries ,因此会自动从seriesColors
中选择第二种颜色。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.