c++ - Qt Progressbar 增加超过它应该的

标签 c++ qt qprogressbar qtimer

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

主窗口.h :

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

主窗口.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。相同的行为。所以这不是计时器!

最佳答案

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

下限(1/60*100) = 1%

下限(2/60*100) = 3%

下限(3/60*100) = 5%

下限(4/60*100) = 6%

因此,将 value() 递增 1 会按顺序增加百分比:1%、2%、2%、1%...

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

我说得对吗?

关于c++ - Qt Progressbar 增加超过它应该的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17410226/

相关文章:

c++ - QProgressBar 和繁重的任务

c++ - Qt QProgressBar - 对齐文本

c++ - SequenceContainer 基类?

c++ - 导致 "non-trivial designated initializers not supported"错误的结构成员顺序

c++ - 如何解决 api-ms-win-core-version-I1-1-1.dll 等 Mincore.lib 依赖项

c++ - QPainter,给文本部分分配不同的颜色

c++ - 提高性能自定义进度条动画

c++ - 我怎样才能得到一串我的语言环境的空格?

javascript - 如何使用 Qt WebEngine 和 QWebChannel?

windows - 未找到 Qt 创建者 : This application has failed to start because MSVCP110. dll