更改QProgressBar中的文本

时间:2011-12-15 02:55:19

标签: qt qprogressbar download-speed

我有一个QProgressBar,我在其中显示了下载进度,但是我想设置它显示下载速度的百分比,将其保留为:

百分比%(downloadspeed KB / s)

有什么想法吗?

4 个答案:

答案 0 :(得分:23)

使QProgressBar文本可见。

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

显示下载进度

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)+"%");
}

答案 1 :(得分:8)

您可以自己计算下载速度,然后构造一个字符串:

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

但是,每次下载速度需要更新时,您都需要这样做。

答案 2 :(得分:3)

我知道这太迟了,但是以防有人迟到。从PyQT4.2开始,您可以只设置setFormat。例如,让它说出maxValue的currentValue(4个中的0个)。您只需要

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

答案 3 :(得分:2)

因为QProgressBar for Macintosh StyleSheet不支持format属性,所以需要跨平台支持,你可以用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);
    }
}