Custom Components
About 475 wordsAbout 2 min
2025-07-17
Component Development
Implement a battery indicator whose progress toggles on click.
Steps:
- Create a custom component class
Create TestLight.cpp and TestLight.h
- The component must inherit from
TpWidget
#ifndef __TEST_LIGHT_H
#define __TEST_LIGHT_H
#include "TpWidget.h"
#include "tpEvent.h"
class TestLight : public TpWidget
{
public:
TestLight(TpWidget *parent);
virtual ~TestLight();
};
#endif- Define variables for maximum bars and current bars
int maxCount_;
int count_;Override
onPaintEventand draw based on the number of bars- Get the painter
TpPainter* painter = event->painter();- Draw background
painter->setPen(_RGB(255, 255, 255)); painter->setBrush(TpBrush(_RGB(255, 255, 255))); painter->drawRect(0, 0, width(), height());- Compute each bar width based on the maximum
int spacing = 3; int singleWidth = (width() - (maxCount_ + 1) * spacing) / maxCount_;- Draw bars according to current level
painter->setPen(_RGB(128, 255, 128)); painter->setBrush(TpBrush(_RGB(128, 255, 128))); for (int i = 0; i < count_; ++i) { int drawX = spacing + i * (singleWidth + spacing); painter->drawRect(drawX, spacing, singleWidth, height() - spacing * 2); }Override
onMousePressEventto capture mouse press and update state
bool TestLight::onMousePressEvent(TpMouseEvent *event)
{
TpWidget::onMousePressEvent(event);
count_++;
if (count_ > maxCount_)
count_ = 0;
return true;
}Component Test
TestLight* light = new TestLight(this);
testButton_->setSize(200, 50);
testButton_->move(150, 300);Demo


完整源码如下
TestLight.h
#ifndef __TEST_LIGHT_H
#define __TEST_LIGHT_H
#include "TpWidget.h"
#include "tpEvent.h"
class TestLight : public TpWidget
{
public:
TestLight(TpWidget *parent);
virtual ~TestLight();
public:
virtual bool onMousePressEvent(TpMouseEvent *event) override;
virtual bool onPaintEvent(TpPaintEvent *event) override;
private:
int maxCount_;
int count_;
};
#endifTestLight.cpp
#include "TestLight.h"
#include "TpPainter.h"
TestLight::TestLight(TpWidget *parent)
: TpWidget(parent), maxCount_(4), count_(0)
{
}
TestLight::~TestLight()
{
}
bool TestLight::onMousePressEvent(TpMouseEvent *event)
{
TpWidget::onMousePressEvent(event);
count_++;
if (count_ > maxCount_)
count_ = 0;
return true;
}
bool TestLight::onPaintEvent(TpPaintEvent *event)
{
TpWidget::onPaintEvent(event);
TpPainter *painter = event->painter();
painter->setPen(_RGB(255, 255, 255));
painter->setBrush(TpBrush(_RGB(255, 255, 255)));
painter->drawRect(0, 0, width(), height());
int spacing = 3;
int singleWidth = (width() - (maxCount_ + 1) * spacing) / maxCount_;
painter->setPen(_RGB(128, 255, 128));
painter->setBrush(TpBrush(_RGB(128, 255, 128)));
for (int i = 0; i < count_; ++i)
{
int drawX = spacing + i * (singleWidth + spacing);
painter->drawRect(drawX, spacing, singleWidth, height() - spacing * 2);
}
return true;
}Copyright
Copyright Ownership:TinyPiXOS
License under:Attribution-ShareAlike 4.0 International (CC-BY-SA-4.0)
