简体   繁体   中英

Draw a dashed circle in QML without Canvas

I want to draw a dashed circle whose radius will grow or shrink depending on a variable. I've only found a Canvas -based solution: Qt (QML) Dashed Circle

I am a little bit surprised to not have found another solution. I'm afraid the Canvas solution will consume too many resources. Is there any other practical way?

If you don't want to use Canvas another approach would be to use QQuickPaintedItem and paint a circle yourself. Implementation would look something like this:

dashcircle.h

#ifndef DASHCIRCLE_H
#define DASHCIRCLE_H

#include <QObject>
#include <QQuickPaintedItem>
#include <QPainter>

class DashCircle : public QQuickPaintedItem
{
    Q_OBJECT
public:
    explicit DashCircle(QQuickItem *parent = nullptr);

    virtual void paint(QPainter *painter);
};

#endif // DASHCIRCLE_H

dashcircle.cpp:

#include "dashcircle.h"

DashCircle::DashCircle(QQuickItem *parent) : QQuickPaintedItem(parent)
{

}

void DashCircle::paint(QPainter *painter)
{
    painter->setPen(QPen(Qt::DashLine));
    painter->drawEllipse(0, 0, width() - 1, height() - 1);
}

Register type:

qmlRegisterType<DashCircle>("Custom", 1, 0, "DashCircle");

Create in qml:

DashCircle {
    x: 50
    y: 50
    width: 50
    height: 50
}

Result:

圆圈

您可以使用我在Qt (QML) Dashed Circle中提到的Qt Quick Shapes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM