Kazuma
Kazuma

Reputation: 1401

Change text displayed by QProgressBar

I use a QProgressBar to show the progress of a download operation. I would like to add some text to the percentage displayed, something like:

10% (download speed kB/s)

Any idea?

Upvotes: 17

Views: 31213

Answers (4)

Josh Pachner
Josh Pachner

Reputation: 521

I know this is super late, but in case someone comes along later. Since PyQT4.2, you can just setFormat. For example to have it say currentValue of maxValue (0 of 4). All you need is

yourprogressbar.setFormat("%v of %m")

Upvotes: 4

lexa-b
lexa-b

Reputation: 1939

Because QProgressBar for Macintosh StyleSheet does not support the format property, then cross-platform support to make, you can add a second layer with QLabel.

    // init progress text label
    if (progressBar->isTextVisible())
    {
        progressBar->setTextVisible(false); // prevent dublicate

        QHBoxLayout *layout = new QHBoxLayout(progressBar);
        QLabel *overlay = new QLabel();
        overlay->setAlignment(Qt::AlignCenter);
        overlay->setText("");
        layout->addWidget(overlay);
        layout->setContentsMargins(0,0,0,0);

        connect(progressBar, SIGNAL(valueChanged(int)), this, SLOT(progressLabelUpdate()));
    }

void MainWindow::progressLabelUpdate()
{
    if (QProgressBar* progressBar = qobject_cast<QProgressBar*>(sender()))
    {
        QString text = progressBar->format();
        int precent = 0;
        if (progressBar->maximum()>0)
            precent = 100 * progressBar->value() / progressBar->maximum();
        text.replace("%p",  QString::number(precent));
        text.replace("%v", QString::number(progressBar->value()));
        QLabel *label = progressBar->findChild<QLabel *>();
        if (label)
            label->setText(text);
    }
}

Upvotes: 3

Lwin Htoo Ko
Lwin Htoo Ko

Reputation: 2406

make the QProgressBar text visible.

QProgressBar *progBar = new QProgressBar();
progBar->setTextVisible(true);

to show the download progress

void Widget::setProgress(int downloadedSize, int totalSize)
{
    double downloaded_Size = (double)downloadedSize;
    double total_Size = (double)totalSize;
    double progress = (downloaded_Size/total_Size) * 100;
    progBar->setValue(progress);

    // ******************************************************************
    progBar->setFormat("Your text here. "+QString::number(progress)+"%");
}

Upvotes: 34

JediLlama
JediLlama

Reputation: 1173

You could calculate the download speed yourself, then construct a string thus:

QString text = QString( "%p% (%1 KB/s)" ).arg( speedInKbps );
progressBar->setFormat( text );

You'll need to do this every time your download speed needs updating, however.

Upvotes: 9

Related Questions