PDA

View Full Version : Using a QTimer to control a QProgressBar



cejohnsonsr
26th August 2010, 21:51
The code that follows is from a trivial app I wrote in order to get familiar with Qt & reacquainted with C++. After getting some help from this forum with the Signals & Slots, I added a QProgressBar & a QTimer to control it (since I don't really have any process to monitor the progress of.) It works but it's kind of clunky. The progress bar doesn't progress smoothly. It updates in intervals of double the last value (i.e. 1,2,4,8,16, etc...) instead of each 1 second increment. I know there must be a better way to code this. Probably a much better way to implement what I'm trying to do. The pertinent portion of the code is pasted below.

Constructive criticism with examples are always appreciated. I really do want to learn (relearn) how to do this properly. It's been several years since I tried to code anything at all.

Thanx,

Ed



void SandSDemo::cancel2Text()
{
QString * cancel2Msg = new QString("Operation confirmed. Proceeding with deletion of all hard drive partitions.");
ui->msgArea->setText(*cancel2Msg);
delete cancel2Msg;
ui->cancel2Button->hide();
counter = 0; // START CODE SNIPPET HERE
updateProgressBar();
}

void SandSDemo::updateProgressBar()
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateProgressBar()));
timer->start(1000);
if(counter <= 100)
{
counter++;
ui->progressBar->setValue(counter);
}
else
{
timer->stop();
delete timer; //END CODE SNIPPET HERE
QString * finalMsg = new QString("Operation completed. All hard drive partitions have been deleted.");
ui->msgArea->setText(*finalMsg);
delete finalMsg;
}
}

Lykurg
26th August 2010, 21:56
You call updateProgressBar every second, then a new timer is created, so 2 timers call your function, then 2 more timers are created (and make a connect), then your function is called 4 times etc. etc. etc. etc. So, you have to create the timer outside updateProgressBar()!

cejohnsonsr
26th August 2010, 22:34
Thank you. That was so obvious AFTER you pointed it out. :o

Ed