QProgressBar updates as function progress

112 Views Asked by At

How to initializa the operation of QProgressBar, I already declare her maximum, minimum, range and values.

I want to assimilate the progress of QProgressBar with the "sleep_for" function.

Current code:

void MainPrograma::on_pushCorre_clicked()
{
    QPlainTextEdit *printNaTela = ui->plainTextEdit;
    printNaTela->moveCursor(QTextCursor::End);
    printNaTela->insertPlainText("corrida iniciada\n");

    QProgressBar *progresso = ui->progressBar;
    progresso->setMaximum(100);
    progresso->setMinimum(0);
    progresso->setRange(0, 100);
    progresso->setValue(0);
    progresso->show();

    WORD wEndereco = 53606;
    WORD wValor = 01;
    WORD ifValor = 0;
    EscreveVariavel(wEndereco, wValor);


//How to assimilate QProgressBar to this function:
std::this_thread::sleep_for(std::chrono::milliseconds(15000));
//StackOverFlow help me please


    EscreveVariavel(wEndereco, ifValor);
2

There are 2 best solutions below

0
On BEST ANSWER

use a QTimer

and in the slot update the value of the progressbar

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    t = new QTimer(this);
    t->setSingleShot(false);
    c = 0;
    connect(t, &QTimer::timeout, [this]()
    {   c++;
        if (c==100) {
            c=0;
        }
        qDebug() << "T...";
        ui->progressBar->setValue(c);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    t->start(100);
}
0
On

I'm not sure about your intentions with such sleep: are you simulating long wait? do you have feedback about progress during such process? Is it a blocking task (as in the example) or it will be asynchronous?

As a direct answer (fixed waiting time, blocking) I think it is enough to make a loop with smaller sleeps, like:

EscreveVariavel(wEndereco, wValor);
for (int ii = 0; ii < 100; ++ii) {
   progresso->setValue(ii);
   qApp->processEvents(); // necessary to update the UI
   std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
EscreveVariavel(wEndereco, ifValor);

Note that you may end waiting a bit more time due to thread scheduling and UI refresh.

For an async task you should pass the progress bar to be updated, or some kind of callback that does such update. Keep in mind that UI can only be refreshed from main thread.