QML知识笔记(八)
这是一个简单的QML&C++案例,实现了一个自定义的电池控件
C++中的电池类如下:
class Cell : public QQuickPaintedItem
{
Q_OBJECT
//设置自定义控件在qml中的属性
Q_PROPERTY(int electric READ getElectricity WRITE setElectricity NOTIFY electricChanged)
Q_PROPERTY(QColor color READ getColor WRITE setColor NOTIFY colorChanged)
Q_PROPERTY(int threshold READ getThreshold WRITE setThreshold NOTIFY thresholdChanged)
public:
explicit Cell(QQuickPaintedItem *parent = nullptr);
//using QQuickPaintedItem::QQuickPaintedItem;
//重写绘制函数
void paint(QPainter*) override;
//电量
void setElectricity(int value) noexcept;
int getElectricity() const noexcept;
//颜色
void setColor(QColor color) noexcept;
QColor getColor() const noexcept;
//阈值
void setThreshold(int value) noexcept;
int getThreshold() const noexcept;
signals:
//电量
void electricChanged();
//颜色
void colorChanged();
//阈值
void thresholdChanged();
private:
int _linewidth = 1; //线宽
int _electric = 70; //电量
QColor _color = Qt::green; //正常电量颜色
QColor _warningcolor = Qt::red; //低电量颜色
int _threshold = 20; //电量阈值
};
void Cell::paint(QPainter* painter)
{
//画笔设置
QPen pen;
pen.setWidth(_linewidth);
pen.setColor(Qt::darkRed);
painter->setPen(pen);
//电池头部
int headwidth = width() * 0.1;
int headheight = height() * 0.3;
auto cellwidth = width() - pen.width() - headwidth;
auto cellheight = height() - pen.width();
//电池
painter->drawRect(0,0,cellwidth,cellheight);
auto electricwidth = (cellwidth - pen.width()) * _electric / 100;
auto electricheight = cellheight - pen.width();
painter->fillRect(pen.width(),pen.width(),electricwidth,electricheight,
_electric > _threshold ? _color : _warningcolor);
//电池头部填充
auto headx = cellwidth + pen.width();
auto heady = height() / 2 - headheight / 2;
painter->fillRect(headx,heady,headwidth,headheight,Qt::black);
}
void Cell::setElectricity(int value) noexcept
{
if(value < 0 || value > 100) return;
_electric = value;
emit electricChanged();
update();
}
int Cell::getElectricity() const noexcept
{
return _electric;
}
void Cell::setColor(QColor color) noexcept
{
_color = color;
emit colorChanged();
}
QColor Cell::getColor() const noexcept
{
return _color;
}
void Cell::setThreshold(int value) noexcept
{
if(value < 0 || value > 100) return;
_threshold = value;
emit thresholdChanged();
update();
}
int Cell::getThreshold() const noexcept
{
return _threshold;
}
main.cpp中要注册电池类
//注册自定义C++类型
qmlRegisterType<Cell>("cell",1,0,"Cell");
main.qml文件如下:
Column{
id: col
anchors.fill: parent
spacing: 10
//自定义电池控件
Cell{
id: cell
anchors.horizontalCenter: parent.horizontalCenter
width: 200
height: 80
electric: slider.value
color: "green"
threshold: 20
}
//滑动条
Slider{
id: slider
value: 25
from: 0
to: 100
anchors.horizontalCenter: parent.horizontalCenter
}
}