【问题标题】:How to change Qt ProgressBar color?如何更改 Qt ProgressBar 颜色?
【发布时间】:2018-10-24 10:48:20
【问题描述】:

我想将进度条的颜色从默认的绿色更改为红色。我有这段代码,但视图是“平面”的,我想实现如下图所示的“3d 效果”:

红色 PB 代码:

QPalette pal = ui->pbExtractionWidget->palette();
pal.setColor(QPalette::Normal, QColor(Qt::red));
QString danger = "QProgressBar::chunk {background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0,stop: 0 #FF0350,stop: 0.4999 #FF0020,stop: 0.5 #FF0019,stop: 1 #FF0000 );border-bottom-right-radius: 5px;border-bottom-left-radius: 5px;border: .px solid black;}";
 ui->pbExtractionWidget->setStyleSheet(danger);

看起来是这样的:

【问题讨论】:

标签: qt qprogressbar


【解决方案1】:

This link provides a way to style the progressbar.

This link provides a way to change gradient color for widgets.

本质上,您只需要正确更改样式表。每个 Chunk 都是进度条的一部分。

或使用QPalette,它使用Base 为小部件的背景着色。正确设置其gradient,然后执行以下操作。

palette.setBrush( QPalette::Base, gradientVariable);
ui->pbExtractionWidget->setPalette(palette);

【讨论】:

    【解决方案2】:
    // In main.cpp
    qDebug() << QStyleFactory::keys();
    // If keys contains e.g. 'Fusion' it would be possible to change color of QProgressBar.
    // On windows default style is 'Windows' and color can only be change with style sheets.
    auto style = QStyleFactory::create("Fusion");
    if (style) {
      app.setStyle(style);
    }
    
    class MyProgressBar final : public QProgressBar {
      void paintEvent(QPaintEvent*) final {
        QStyleOptionProgressBar option{};
        initStyleOption(&option);
        option.textAlignment = Qt::AlignHCenter;
        option.palette.setColor(QPalette::Highlight, QColor("lightskyblue"));
        option.palette.setColor(QPalette::HighlightedText, option.palette.color(QPalette::Text));
        QPainter painter{this};
        style()->drawControl(QStyle::CE_ProgressBar, &option, &painter, this);
      }
    };
    

    【讨论】:

      【解决方案3】:

      你必须正确设置样式表,使用下面的样式表代码

      QString danger = "QProgressBar::chunk: horizontal {border-radius: 3px; background: QLinearGradient(X1:0, y1:0.966136, x2:0, y2:0, stop:0.609721 rgba(242, 53, 53, 255), stop:0.691923 rgba(240, 151, 141, 252));border: .px solid black;}";
      
      ui->progressBar->setStyleSheet(danger);
      

      【讨论】:

        猜你喜欢
        • 2012-11-01
        • 2012-11-08
        • 2010-12-01
        • 2011-06-08
        • 1970-01-01
        • 2016-01-30
        • 1970-01-01
        • 2011-02-07
        • 1970-01-01
        相关资源
        最近更新 更多