在 QML 中绘制圆弧/圆扇区? [英] Draw an arc/circle sector in QML?

查看:43
本文介绍了在 QML 中绘制圆弧/圆扇区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以使用以下代码在 QML 中画一个圆:

I know that it is possible to draw a circle in QML using the following code:

Rectangle {
     width: 150
     height: 150
     anchors.horizontalCenter: parent.horizontalCenter
     anchors.top: parent.top
     color: "#095e7b"
     border.color: "#0a2f4a"
     border.width: 2
     radius: width*0.5
}

我的问题是:如果我需要画一个圆的扇区怎么办.(Pizza Slices)并使这些切片中的每一个都可点击?我可以只使用 QML 吗?

My question is: what if I need to draw a sector of a circle. (Pizza Slices) and make each of these slices clickable? Can I do this using QML only?

推荐答案

是的,使用 Canvas(和 Context2D):

Yes, using Canvas (and Context2D):

import QtQuick 2.3

Rectangle {
    width: 400
    height: 400

    Canvas {
        anchors.fill: parent
        onPaint: {
            var ctx = getContext("2d");
            ctx.reset();

            var centreX = width / 2;
            var centreY = height / 2;

            ctx.beginPath();
            ctx.fillStyle = "black";
            ctx.moveTo(centreX, centreY);
            ctx.arc(centreX, centreY, width / 4, 0, Math.PI * 0.5, false);
            ctx.lineTo(centreX, centreY);
            ctx.fill();

            ctx.beginPath();
            ctx.fillStyle = "red";
            ctx.moveTo(centreX, centreY);
            ctx.arc(centreX, centreY, width / 4, Math.PI * 0.5, Math.PI * 2, false);
            ctx.lineTo(centreX, centreY);
            ctx.fill();
        }
    }
}

我实际上是从 this 回答,因为 Qt 的 Canvas 实现了 HTML5 Canvas API.这使得在网络上查找示例变得非常容易;例如,只需搜索draw pie slice blah html5 canvas".

I actually took the code for this from this answer, as Qt's Canvas implements the HTML5 Canvas API. This makes it really easy to find examples on the web; just search for "draw pie slice blah html5 canvas", for example.

对于鼠标检测,你必须放弃你的数学技能......

For the mouse detection, you'll have to brush off your maths skills...

...或者只是从 这里.:)

... or just steal the code from here. :)

请注意,Canvas 仅在调整大小或 requestPaint() 被调用,所以如果你想根据鼠标位置改变切片的颜色,你需要调用该函数来查看颜色变化.

Note that Canvas only repaints when it's resized, or when requestPaint() is called, so if you want to change the colour of a slice depending on the mouse position, you'll need to call that function to see the colour change.

这篇关于在 QML 中绘制圆弧/圆扇区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆