在调用qml注册类的cpp里添加
//注册绘制虚线框类
qmlRegisterType<PaintLine>("PaintLine",1, 0, "PaintLine");
paintline.h
#ifndef PAINTLINE_H
#define PAINTLINE_H
#include <QQuickPaintedItem>
#include <QPen>
#include <QPainter>
class PaintLine:public QQuickPaintedItem
{
Q_OBJECT
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)//注册qml中属性color
Q_PROPERTY(int penWidth READ penWidth WRITE setPenWidth NOTIFY penWidthChanged)//注册qml中属性penWidth
Q_PROPERTY(QRectF rect READ rect WRITE setRect NOTIFY recChanged)//注册qml中属性rect
public:
PaintLine(QQuickItem *parent = nullptr);
QColor color() const;
void setColor(const QColor &color);
int penWidth() const;
void setPenWidth(const int &penWidth);
QRectF rect() const;
void setRect(const QRectF &rec);
QPen pen() const;
void setPen(const QPen &pen);
protected:
void paint(QPainter *painter);
private:
QColor m_color = "#EEEEEE";
int m_penWidth = 2;
QRectF m_rec;
QPen m_pen;
QVector<qreal> dashes;
qreal space;
signals:
void colorChanged();
void penWidthChanged();
void recChanged();
void penChanged();
};
#endif // PAINTLINE_H
paintline.cpp
#include "paintline.h"
PaintLine::PaintLine(QQuickItem *parent)
{
}
QColor PaintLine::color() const
{
return m_color;
}
void PaintLine::setColor(const QColor &color)
{
m_color = color;
emit colorChanged();
}
int PaintLine::penWidth() const
{
return m_penWidth;
}
void PaintLine::setPenWidth(const int &penWidth)
{
m_penWidth = penWidth;
emit penWidthChanged();
}
QRectF PaintLine::rect() const
{
return m_rec;
}
void PaintLine::setRect(const QRectF &rec)
{
m_rec = rec;
emit recChanged();
this->update();
}
void PaintLine::paint(QPainter *painter)
{
m_pen.setStyle(Qt::DashLine);
m_pen.setCapStyle(Qt::RoundCap);
m_pen.setJoinStyle(Qt::RoundJoin);
m_pen.setWidth(m_penWidth);
m_pen.setBrush(m_color);
space = 2;
dashes << 2 << space ;
m_pen.setDashPattern(dashes);
painter->setPen(m_pen);
painter->drawRect(m_rec);
}
qml中调用方式
import PaintLine 1.0//包含注册模块
PaintLine{
id: paintRec
anchors.fill: parent
color: "#FFFFFF"
penWidth: lineWidth
rect: Qt.rect(centernRecX, centernRecY, centernRecWidth-1-penWidth, centernRecHeight-1-penWidth)
}