Files
Radio/module/radio/component/ProgressBar.cpp
T
2026-07-29 12:30:40 +08:00

89 lines
3.0 KiB
C++

#include "ProgressBar.h"
#include <QPainter>
Progress_Bar::Progress_Bar(const QVector<Tick>& tick_list, QWidget *parent) : QWidget(parent), tick_list(tick_list) {
setAttribute(Qt::WA_OpaquePaintEvent, true);
timer = startTimer(30);
}
double Progress_Bar::get_draw_width(double value) {
int n = tick_list.size();
int i = 1;
for(; i < n - 1; ++i) {
double cur = tick_list[i].value;
if(value < cur || qFuzzyCompare(value, cur)) {
break;
}
}
int lower_offset = i - 1;
int upper_offset = i;
double lower = tick_list[lower_offset].value;
double upper = tick_list[upper_offset].value;
double w_step = (double)QWidget::width()/(double)(n-1);
double last_rate = qMax(0.0, (value - lower)/(upper - lower));
double draw_width = w_step * (last_rate + lower_offset);
QString ticks;
for(Tick& tick : tick_list) {
ticks.append(" " + QString::number(tick.value));
}
// qDebug() << QString("%1->[%2,%3] i=%4 n=%5 draw_width:%6 width:%7 ticks:%8 w_step:%9 last_rate:%10")
// .arg(value).arg(lower).arg(upper).arg(i).arg(n).arg(draw_width).arg(width()).arg(ticks)
// .arg(w_step).arg(last_rate);
return draw_width;
}
void Progress_Bar::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setPen(Qt::NoPen);
painter.fillRect(rect(), QApplication::style()->standardPalette().brush(QPalette::Window));
painter.setPen(QPen(Qt::black));
auto w = (double)QWidget::width();
auto hh = (double)height()/2;
int n = tick_list.size();
int tick_w = 1;
double draw_width = get_draw_width(value);
// 背景
painter.fillRect(0, 0, draw_width - tick_w - 4, height()/2, Qt::black);
int cur_x = 0;
// 进度条
while(cur_x + tick_w + 4 < draw_width){
painter.fillRect(cur_x, 0, tick_w, height()/2, Qt::gray);
cur_x += tick_w + (int)tick_space_w;
}
int line_y = (int)hh + 2;
painter.fillRect(cur_x -(int)tick_space_w , 0, 4, line_y - 0, Qt::yellow);
painter.drawLine(0, line_y , (int)w, line_y);
// 画刻度
QFont font;
font.setBold(true);
QFontMetrics fm(font);
for(int i = 0; i < n; ++i){
int tick_x = (int)((double)(QWidget::width() * i)/(double)(n - 1));
int text_w = fm.horizontalAdvance( tick_list[i].text);
int text_x;
if(i == n - 1) {
text_x = tick_x - text_w;
tick_x -=1;
} else if( i == 0) {
text_x = tick_x;
} else {
text_x = tick_x - text_w/2;
}
painter.setPen(Qt::black);
painter.drawLine(tick_x, line_y, tick_x, (line_y + 5));
painter.setPen(tick_list[i].color);
painter.setFont(font);
painter.drawText(QRectF(text_x, line_y, text_w, line_y), Qt::AlignCenter, tick_list[i].text);
}
}
void Progress_Bar::timerEvent(QTimerEvent *event) {
if(event->timerId() == timer) {
if(set_value) set_value();
update();
}
QObject::timerEvent(event);
}