show a simple progress bar in C++ - c++

Here is the problem:
I want to show a progress bar (just as a text like "Remaining 35%...") during a C++ function execution. I've done the first part which is the progress bar but the problem is how do I show the progress bar during the other functions execution?
I just want to start showing the bar when execution enters a specific function and reach 100% when leaving the function.
How do I do this in C++? any suggestion?
thanks in advance!
/Niklas

Use a separate thread to update the progress bar. That should give "near real" progress of your application.

There are two things to consider. First is, when do you update your progress bar? In general this can be done by dividing the work your function does into ticks, and then use a tick-count that you increase every time the function has advanced one tick. One example would be this:
void SomeFunction() {
for ( int i = 0; i < 1337; i++ ) {
// do important stuff
ProgressBar.IncreaseTickCount();
}
}
The caller would then do something like this:
ProgressBar.SetNumberOfTicks( 1337 );
SomeFunction();
This way, the progress bar would be able to recalculate its value at every iteration of the loop. How this is presented on the screen depends on your GUI-Framework. As has been suggested by #Amit and the comments to his answer, you will most likely have the function run in a worker-thread, and the UI-thread will update the progress bar continuously. In this case make sure that the tick-counter is thread-safe.

A simple text-based stdout tic style progress bar can be found in a single file at ezProgressBar
. You can wrap it in a thread if you'd like. One nice feature is that is does minimal printing to a single line so overhead is pretty cheap and you don't need to play games with finding the magic "reset cursor to beginning of line" character like '\r'.

Related

why `OnWorkerEvent` is used in `wxProgressDialog`?

I have to display a progress bar using wxWidgets. Currently I am doing this :
m_dlgProgress = new wxGenericProgressDialog(wxString("Heading"), wxString("Message"), max, this, wxPD_APP_MODAL | wxPD_AUTO_HIDE | wxPD_SMOOTH);
for (int i = 0; i <= max; i++)
{
cont = m_dlgProgressConfig->Update(i);
i += max / 7;
wxMilliSleep(200);
}
callingSomeFunctionFromBackend();
//after this function is executed I am updating dialogue with its maximum value
cont = m_dlgProgressConfig->Update(max);
Is this correct way to display progress bar? I have seen some codes which create a thread and use OnWorkerEvent to update progress bar. Why do they create a thread. What I have done is correct or will it cause any problem further?
Your code is mostly fine, although you should really create the dialog on stack and not allocate it on the heap (especially without ever deleting it) and it's not clear why do you use wxGenericProgressDialog instead of wxProgressDialog.
But using a separate thread is preferable because it keeps your program GUI responsive while in your example it will be blocked for 200ms at a time and also for however long "some function from backend" is going to take. If this is acceptable for you, you can keep it like this, but using a background thread often results in a better user experience -- even though it requires more effort from the programmer.

How to show "waiting" while files are loaded in a Qt application?

I'm selecting and loading some big Dicom files on my program. The whole loading process takes a long time(depends on the number of files, but the whole process can take more than minutes if the files are many). I want show a "waiting symbol" or something like that when the file uploading is going on. I searched for it, but I didn't get anything definite.
My code for the selection and uploading part is as below:
void MainWindow::showTheSelectedList()
{
QFileDialog * fileDialog = new QFileDialog(this);
fileDialog->setFileMode(QFileDialog::ExistingFiles);
QListView* list = fileDialog->findChild<QListView*>("listView");
if(list)
{
list->setSelectionMode(QAbstractItemView::MultiSelection);
}
QTreeView* tree = fileDialog->findChild<QTreeView*>();
if(tree)
{
tree->setSelectionMode(QAbstractItemView::MultiSelection);
}
if(fileDialog->exec())
{
if(fileDialog->selectedFiles().size()>0)
{
int listsize=stringList.size();
for(int i=0;i<listsize;i++)
{
// get the name of the file
// check if the file is dicom
// upload if the file is dicom
// after uploading, get the pixel data of that file
// use the pixel data and make a icon out of it
//then insert the icon in an a QTablewView
}
}
}
//show the QtableView
}
Could you please instruct me where and how I can show the waiting sign or symbol while the uploading part is running?
Thanks
I think you are looking for the QProgressBar class. The documentation makes it clear below. You will need to set up the minimum and maximum values, and it will do the job for you.
The QProgressBar widget provides a horizontal or vertical progress bar.
A progress bar is used to give the user an indication of the progress of an operation and to reassure them that the application is still running.
The progress bar uses the concept of steps. You set it up by specifying the minimum and maximum possible step values, and it will display the percentage of steps that have been completed when you later give it the current step value. The percentage is calculated by dividing the progress (value() - minimum()) divided by maximum() - minimum().
You can specify the minimum and maximum number of steps with setMinimum() and setMaximum. The current number of steps is set with setValue(). The progress bar can be rewound to the beginning with reset().
If minimum and maximum both are set to 0, the bar shows a busy indicator instead of a percentage of steps. This is useful, for example, when using QNetworkAccessManager to download items when they are unable to determine the size of the item being downloaded.
I do not think much more details can be provided based on the question as the worker loop seems to be commented without actual code being provided in there, but this documentation should make it clear either way.
Note that I would personally even move the worker loop into an own worker thread if it is that hefty that it deserves a progressbar. As for the progressbar, you would probably write something like this:
QProgressBar bar(this);
bar.setRange(maximum, maximum);
bar.setValue(minimum);
bar.show();
Dialog box:
My novice suggestion would be to use progress bar inside your for loop and increment the progress bar as each file finishes loading.
Let me know if you need more detail.

C++ parallel loops

I'm making a console game called alien spaceships as a homework. It should look something like this http://img74.imageshack.us/img74/8362/alieninvadersfdcl192720mu1.jpg .
So far so good I ain't allowed to use classes nor objects => only functions and arrays.
I have one while loop that checks the buttons I press on the keyboard and according to the button applies some functions.
The problem comes when I try to shoot a missle because it's done with a "for" loop and when I shoot I can't move. Can someone give me an idea how the model is supposed to look like and how can I make something like this work. I don't think it's needed to post my code, but if you want I'll post it.
I assume that you're not willing to play with multiple threads. It is not mandatory for a simple game like this and would add a bit of complexity.
So generic loop for monothreaded game is:
state new_state = createInitialState();
do
{
input = readInput(); // non blocking !
new_state = modifyState(input, new_state);
updateScreen(new_state);
}
while (!exitCondition(input));
None of these functions should loop for long.
In your case, the missile position should be updated in modifyState taking into account the time since the last modifyState.
I assume you use a matrix to store all the data, and periodically you print the content of the matrix (that's how you create a console game).
So, your code should look something like this:
render()
{
update_position(x,y);
if(missile_fired)
update_missile_position();
}
main()
{
for(;;)
{
read_input(&x,&y);
render();
draw_image();
}
}

QTProgressBar not updating when running setValue

I have a for-loop which is setting the value of the progress bar on every iteration.
The for-loop executes the setProgress-method described here:
void setProgress(int progStep){
progressBar->setValue(progStep);
progStep++;
QTextStream(stdout) << progStep << " " << progSum << endl;
}
I can print out that last line, so the method is executed but the GUI of the progress bar is not updated every time.
When I have a maximum value of 25 (and min 0), the method prints every number from 0-25. My goal is to have the progress bar to then show 25 different percentage values during this execution.
Structure:
for(.....) {
.....
.....
setProgress(progStep);
}
What actually happens is that it updates the progress bar with percentage values about 2-3 times. The for-loop takes about 30 seconds so it should definitely be able to make 25 percentage updates.
How can I solve this?
You have to call QApplication::processEvents() after calling setProgress(progStep), to let the GUI thread update the progress bar.
It seems you're simply calling several time setProgress() without running the event loop, thus the GUI is not updated.
Call QApplication::processEvents() after setProgress() in order to update the GUI.
If you want setProgress() to update the GUI whatever the situation is, you can call QApplication::processEvents() in the body of setProgress(), after the progress bar update part.

If timer is started and running , donot reset it once again using flex3

I'm having 2 problems.
1 - I have a text area in which I am matching a string. If it matches then a timer will start. But that condition will likely be satisfied more than once, so I would like to give a condition that if timer is already running don't do anything, if(!timer.running) then start timer. But it still resets the timer every time.
2 - I have a chat window. For every user activity a sentence will be displayed to it. For each added sentence I have to perform some actions. So i have given conditions and actions to be performed for each sentence in a single function, but the problem is every time the previous already executed commands are also executed one more time. (for example above problem 1.)so once it matches the 1st string it should start search from 2nd line in the text area, i think this can do the trick. any help will be appreciated.
public function updateMessage(updateMsg:String) : void
{
userActivities.text+=updateMsg+"\n";
if(userActivities.text.indexOf("user connected",0)!=-1)
{
userTimer=new Timer(delay);
if(!userTimer.running)
{
basetmr=getTimer();
userTimer.addEventListener(TimerEvent.TIMER,chkUserActivities);
userTimer.start();
}
else
{
//trace("timerCount.."+userTimer.currentCount);
}
}
else if(userActivities.text.indexOf("user changed the image",0)!=-1 )
{
userActivities.text+="Click ReleaseDetails button to release your details to visitor";
}
else if(userActivities.text.indexOf("user quit the session",0)!=-1)
{
userTimer.stop();
}
}
Your code is wrong. Here is some comments:
// this line creaets a new timer
userTimer=new Timer(delay);
// no code here to start the timer running
// userTimer.running will always be false and this condition will always be true
if(!userTimer.running)
I bet if you change the first line of your method to something like this:
if(userTimer){
userTimer=new Timer(delay);
}
It would work because you will not be re-initializing the timer on ever method call.
As it stands you are creating a new timer and then checking if its running, so I think part one would be improved by changing from
userTimer=new Timer(delay);
if(!userTimer.running)
{
basetmr=getTimer(); //etc
To something like
if(!userTimer.running)
{
userTimer=new Timer(delay);
basetmr=getTimer(); //etc
For part 2 I'm not familiar enough with flex to be able to help, but instead of checking userActivities.text you want to check the latest subsection of it, such as just the last sentence.