自定义组件
2025-07-17
组件开发
实现一个点击切换进度的电量指示灯。
步骤如下所示:
- 创建自定义组件类
创建testLight.cpp和testLight.h文件
- 组件类需继承于tpChildWidget
#ifndef __TEST_LIGHT_H
#define __TEST_LIGHT_H
#include "tpChildWidget.h"
#include "tpEvent.h"
class testLight : public tpChildWidget
{
public:
testLight(tpChildWidget *parent);
virtual ~testLight();
};
#endif
- 定义电量最大格数和当前显示格数变量
int maxCount_;
int count_;
重写onPaintEvent事件,根据电量格数绘制效果
- 获取绘制画笔
tpCanvas* painter = event->canvas();
- 绘制底色
painter->box(0, 0, width(), height(), _RGB(255, 255, 255));
- 根据最大格数计算每个格子的宽度
int spacing = 3; int singleWidth = (width() - (maxCount_ + 1) * spacing) / maxCount_;
- 根据当前电量绘制电量格子
for (int i = 0; i < count_; ++i) { int drawX = spacing + i * (singleWidth + spacing); painter->box(drawX, spacing, drawX + singleWidth, height() - spacing, _RGB(128, 255, 128)); }
重写onMouseKeyEvent捕获鼠标点击事件,获取鼠标点击状态
if (event->button() == BUTTON_LEFT)
{
if (event->state())
{
count_++;
if (count_ > maxCount_)
count_ = 0;
}
}
组件测试
testLight* light = new testLight(this);
testButton_->setSize(200, 50);
testButton_->move(150, 300);
演示效果


完整源码如下
testLight.h
#ifndef __TEST_LIGHT_H
#define __TEST_LIGHT_H
#include "tpChildWidget.h"
#include "tpEvent.h"
class testLight : public tpChildWidget
{
public:
testLight(tpChildWidget *parent);
virtual ~testLight();
public:
virtual bool onMouseKeyEvent(tpMouseKeyEvent *event) override;
virtual bool onPaintEvent(tpObjectPaintEvent *event) override;
private:
int maxCount_;
int count_;
};
#endif
testLight.cpp
#include "testLight.h"
#include "tpCanvas.h"
testLight::testLight(tpChildWidget *parent)
: tpChildWidget(parent), maxCount_(4), count_(0)
{
}
testLight::~testLight()
{
}
bool testLight::onMouseKeyEvent(tpMouseKeyEvent *event)
{
tpChildWidget::onMouseKeyEvent(event);
if (event->button() == BUTTON_LEFT)
{
if (event->state())
{
count_++;
if (count_ > maxCount_)
count_ = 0;
}
}
return true;
}
bool testLight::onPaintEvent(tpObjectPaintEvent *event)
{
tpChildWidget::onPaintEvent(event);
tpCanvas *painter = event->canvas();
painter->box(0, 0, width(), height(), _RGB(255, 255, 255));
int spacing = 3;
int singleWidth = (width() - (maxCount_ + 1) * spacing) / maxCount_;
for (int i = 0; i < count_; ++i)
{
int drawX = spacing + i * (singleWidth + spacing);
painter->box(drawX, spacing, drawX + singleWidth, height() - spacing, _RGB(128, 255, 128));
}
return true;
}