QT c++绘制虚线在qml显示方法qml注册C++类

这篇博客介绍了如何在C++中定义一个QML类型`PaintLine`,用于在QML界面中绘制虚线框。通过继承`QQuickPaintedItem`,实现了颜色、线宽和矩形区域等属性,并在`paint`方法中设置虚线样式进行绘制。在QML中可以通过导入模块并设置属性来使用这个自定义组件。
摘要由CSDN通过智能技术生成

在调用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)
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值