改进性能自定义进度条动画

Improve performance custom progress bar animation

本文关键字:动画 自定义 性能      更新时间:2023-10-16

我想要一个自定义进度条,它的进度通过自定义动画进行更改。我会有很多这个小部件的实例,所有这些都应该平稳快速地运行。

我的第一次尝试是使用常规的QProgressBar,通过使用样式表对其进行自定义,然后使用QPropertyAnimation来动画化状态的变化。

这很好,但速度非常慢。比方说,我以0%的值开始动画,然后达到50%,并希望在500毫秒的持续时间内完成。它一点也不顺利,但有三个明显可区分的步骤。如果我放弃样式表,它将足够顺利地工作。

好吧,似乎可以很好地使用QProgressBar的派生类,它比使用样式表快得多,尽管我必须自定义调整宽度和高度:

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);
}

制作这个栏的动画是简单而快速的:

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

仍然可以获得反馈或更好的解决方案!