Grégoire Borel
Grégoire Borel

Reputation: 2028

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?

Upvotes: 2

Views: 1829

Answers (2)

Gleb Ignatev
Gleb Ignatev

Reputation: 159

You could use Qt Quick Shapes as I've mentioned in Qt (QML) Dashed Circle.

Upvotes: 0

Eligijus Pupeikis
Eligijus Pupeikis

Reputation: 1125

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:

circle

Upvotes: 8

Related Questions