前言
本文章介绍使用QQuickPaintedItem
绘制自定义的qml类型。
QQuickPaintedItem类需要重写paint函数,在重写的paint函数里使用QPainter进行绘制
一、创建QQuickPaintedItem
创建一个QQuickPaintedItem子类,本文示例绘制一个BandPower图元来示例
cbandpoweritem.h
//cbandpoweritem.h
#ifndef CBANDPOWERITEM_H
#define CBANDPOWERITEM_H
#include <QQuickPaintedItem>
#include "PropertyHead.h"
class CBandPowerItem : public QQuickPaintedItem
{
Q_OBJECT
BJ_PROPERTY(double,centerFreqPos)
BJ_PROPERTY(double,spanFreqPos)
BJ_PROPERTY(double,bandPowerPos)
public:
CBandPowerItem(QQuickItem *parent = nullptr);
virtual void paint(QPainter *painter);
};
#endif // CBANDPOWERITEM_H
代码中的BJ_PROPERTY
是一个自定义属性的宏,包括set,get和信号的宏,感兴趣的可以跳转Qt自定义属性宏这里去看,了解宏的使用。
cbandpoweritem.cpp
//cbandpoweritem.cpp
#include "cbandpoweritem.h"
#include <QPainter>
#include <QBrush>
#include <QPen>
#include <QFont>
CBandPowerItem::CBandPowerItem(QQuickItem *parent )
:QQuickPaintedItem(parent)
{
connect(this,&CBandPowerItem::centerFreqPosChanged,this,[=](){update();});
connect(this,&CBandPowerItem::spanFreqPosChanged,this,[=](){update();});
connect(this,&CBandPowerItem::bandPowerPosChanged,this,[=](){update();});
}
void CBandPowerItem::paint(QPainter *painter)
{
if(painter == nullptr)
return;
painter->save();
double dStartFreqPos = m_centerFreqPos - m_spanFreqPos / 2;
double dStopFreqPos = m_centerFreqPos + m_spanFreqPos / 2;
painter->setPen(Qt::blue);
//画线
painter->drawLine(QPointF(dStartFreqPos,0),QPointF(dStartFreqPos,height()));
painter->drawLine(QPointF(dStopFreqPos,0),QPointF(dStopFreqPos,height()));
painter->drawLine(QPointF(dStartFreqPos,m_bandPowerPos),QPointF(dStopFreqPos,m_bandPowerPos));
//画字体
int nTextHeight = 15;
QFont ft;
ft.setPixelSize(nTextHeight);
painter->setFont(ft);
painter->drawText(QRectF(QPointF(dStartFreqPos,m_bandPowerPos - nTextHeight),QSizeF(m_spanFreqPos,nTextHeight)),
Qt::AlignHCenter | Qt::AlignBottom,
QString("BW:%1").arg(m_bandPowerPos));
painter->restore();
}
二、注册qml类型
在qml使用CBandPowerItem类时,需要注册qml类型,在main.cpp里
注册类型
//注册类型
qmlRegisterType<CBandPowerItem>("MyItem",1,0,"BandPowerItem");
QQuickView view;
const QUrl url(QStringLiteral("qrc:/main.qml"));
view.setSource(url);
view.show();
三、在main.qml使用BandPowerItem
使用Item
import QtQuick 2.12
import QtQuick.Window 2.12
import QtCharts 2.14
import MyItem 1.0
Rectangle {
visible: true
width: 640
height: 480
color: "#2795e9"
BandPowerItem{
id:id_bandPowerItem
centerFreqPos: 200
spanFreqPos: 100
bandPowerPos: 200
anchors.fill: parent
}
}
效果图:
例如:以上就是今天要分享的内容,本文仅仅简单介绍了QQuickPaintedItem的使用,绘制了一个简单的Item加载到qml里。涉及了qml类型注册和绘制的一些知识。