Qt Progressbar增量超过预期

时间:2013-07-01 17:26:18

标签: c++ qt qprogressbar qtimer

所以我想要的只是用计时器增加进度条。但不知何故,它增加了进度条的数量。

mainwindow.h:

Class MainWindow {
//...
private slots:
//...
    void update();
private:
    Ui::MainWindow *ui;
    QTimer *timer;
    unsigned int counter;
};

mainwindow.cpp:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    timer = new QTimer(this);
    counter = 0;
    connect(timer, SIGNAL(timeout()), this, SLOT( update() ) );
}

void MainWindow::on_actionStart_triggered()
{
    if( ui->txtTime->text().isEmpty() || (ui->txtTime->text().toInt() == 0) )
    {
        QMessageBox::warning(this, "Error", "Could not start the timer.", QMessageBox::Ok);
        return;
    }

    ui->cmdStart->setEnabled(false);
    timer->start(ui->txtTime->text().toInt() * 60000  / 60);
}


void MainWindow::update()
{
    counter++;
    ui->progressBar->setValue( counter ); //Should be incremented by one
    if( ui->progressBar->value() == 60 )
    {
        timer->stop();
        Phonon::MediaObject *music = Phonon::createPlayer(Phonon::MusicCategory,
                                                          Phonon::MediaSource( ":/Music/" + ui->chkMusic->currentText() ));
        music->play();  //Playing music
        delete timer;
    }
}

我注意到调试器的进度条值为6,而计数器只有值4.此外,它先增加1,然后是2,然后再增加2,然后再增加1,依此类推。我做错了什么?!

编辑: 我认为这是进度条。我把动作改为:

void MainWindow::on_actionStart_triggered()
{
    if( ui->txtTime->text().isEmpty() || (ui->txtTime->text().toInt() == 0) )
    {
        QMessageBox::warning(this, "Error", "Could not start the timer.", QMessageBox::Ok);
        return;
    }

   // ui->cmdStart->setEnabled(false);
   // ui->progressBar->setMaximum( ui->txtTime->text().toInt() * 60 );
   // timer->start( 1000 );
    counter++;
    ui->progressBar->setValue( counter );
}

自从我评论出来之后,没有计时器会启动。总是当我点击操作按钮时,它会将进度条增加1,然后是2,然后再增加2,然后再增加1.相同的行为。所以这不是计时器!

1 个答案:

答案 0 :(得分:1)

我认为你不匹配QProgressBar值(minimum()和maximum()之间的整数)和显示的进度百分比,大致是(value-min)/(max-min)

楼层(1/60 * 100)= 1%

楼层(2/60 * 100)= 3%

楼层(3/60 * 100)= 5%

楼层(4/60 * 100)= 6%

因此,将值()递增1会增加序列的百分比:1%,2%,2%,1%...

如果要在计数器达到60时显示60%,则需要setMaximum(100)

我是对的吗?