Search code examples
c++windowsqtthread-sleepqprogressbar

QProgressBar updates as function progress


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);

Solution

  • 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);
    }