IceFire
IceFire

Reputation: 4137

Improve performance custom progress bar animation

I am looking to have a customized progress bar whose progress changes via a custom animation. I will have quite a number of instances of this widget and all of them should run smoothly and fast.

My first attempt was to use a regular QProgressBar, customize it by using a stylesheet and then using QPropertyAnimation to animate the change in status.

This works fine but is extremely slow. Say, I start my animation at a value of 0% and go up to 50% and want this to be accomplished during a duration of 500 msec. It is not smooth at all, but there are three clearly distinguishable steps. If I drop the stylesheet, it will work smoothly enough.

Upvotes: 0

Views: 1034

Answers (1)

IceFire
IceFire

Reputation: 4137

Well, what seems to work fine is using a derived class of QProgressBar, it is much faster than using stylesheets, although I have to custom-adjust the width and height:

void ColorBar::paintEvent(QPaintEvent *pe)
{
    QRect region = pe->rect();
    QPainter painter(this);

    QColor borderColor;
    borderColor.setNamedColor("#a0a0a0");
    QColor lightColor = QColor(255, 255, 255);
    QColor darkColor = QColor(225, 225, 225);

    int barHeight = static_cast<int>(height() * 1. / 4. + 0.5);

    QRect drawRect(0, static_cast<int>(height() / 2. - barHeight / 2. + 0.5), width() * .9 * value() / maximum(), barHeight);

    QLinearGradient g(drawRect.topLeft(), drawRect.bottomLeft());
    g.setColorAt(0., lightColor);
    g.setColorAt(1., darkColor);

    painter.setPen(QPen(borderColor));
    painter.setBrush(QBrush(g));

    painter.drawRect(drawRect);
}

Animating this bar is then straightforward and fast:

        QPropertyAnimation* x = new QPropertyAnimation(percentageBar, "value");
        x->setStartValue(percentageBar->value());
        x->setEndValue(newValue);
        x->setDuration(500);
        x->start();

Still open for feedback or better solutions!

Upvotes: 1

Related Questions