How to add a rectangle to a QML ChartView?

眉间皱痕 提交于 2021-02-16 18:22:58

问题


I want to put a number of rectangles as overlays to show regions of interest on a ChartView of ScatterSeries. However when I try to do this it is clearly using a different coordinate system to that of the ScatterSeries as it is drawn in a completely different place.

For example the following is intended to draw a rectangle that captures all of the ScatterSeries but it just draws a small green rectangle top left as shown in the screenshot.

        ChartView {
            id: view
            Layout.fillWidth : true
            Layout.fillHeight : true
            Rectangle {
                id: rec
                x: 30
                y: 50
                width: 40
                height: 10
                color: "green"
            }
            ScatterSeries{
                id: series
                XYPoint { x: 30; y: 50 }
                XYPoint { x: 50; y: 60 }
                XYPoint { x: 60; y: 50 }
                XYPoint { x: 70; y: 60 }
                axisX: ValueAxis {
                    min: 0
                    max: 100
                }
                axisY: ValueAxis {
                    min: 0
                    max: 100
                }
            }

The documentation suggests that the rectangle should use the coordinate system of the parent ChartView. I assume I actually want it to use the coordinate system of the ChartView scene. How do I do this?


回答1:


To translate from the ScatterSeries coordinate system to pixel coordinates to place a child in ChartView use mapToPosition(...):

function updateRectangle() {
    var topLeftPoint = view.mapToPosition(Qt.point(30,60), series)
    var bottomRightPoint = view.mapToPosition(Qt.point(70,50), series)

    rec.x = topLeftPoint.x
    rec.y = topLeftPoint.y

    rec.width  = bottomRightPoint.x - topLeftPoint.x
    rec.height = bottomRightPoint.y - topLeftPoint.y
}

Where series is your ScatterSeries and rec is your Rectangle.

Invoke the update function whenever the chart points get recalculated (e.g. after creation and size changes).

See also related question How to map QChart coordinate to QChartView point?



来源:https://stackoverflow.com/questions/57414937/how-to-add-a-rectangle-to-a-qml-chartview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!