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

时间:2016-05-16 08:46:19

标签: c++ qt qt5 qprogressbar

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

我的第一次尝试是使用常规QProgressBar,使用样式表对其进行自定义,然后使用QPropertyAnimation为状态更改设置动画。

这种方法很好,但速度极慢。比如,我以0%的值开始我的动画并且达到50%并希望在500毫秒的持续时间内完成。它根本不光滑,但有三个明显可区分的步骤。如果我删除样式表,它将足够顺利。

1 个答案:

答案 0 :(得分:1)

嗯,似乎工作正常的是使用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();

仍然可以提供反馈或更好的解决方案!

相关问题