在没有Canvas的QML中绘制虚线圆圈

问题描述 投票:2回答:1

我想绘制一个虚线圆,其半径将根据变量增大或缩小。我只发现了一个基于Canvas的解决方案:Qt (QML) Dashed Circle

我没有找到另一个解决方案,我有点惊讶。我担心Canvas解决方案会消耗太多资源。还有其他实用的方法吗?

qt canvas qml
1个回答
6
投票

如果你不想使用Canvas,另一种方法是使用QQuickPaintedItem并自己画一个圆圈。实现看起来像这样:

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);
}

注册类型:

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

在qml中创建:

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

结果:

circle

© www.soinside.com 2019 - 2024. All rights reserved.