Coding progress bar advice

2019-02-27 11:25发布

问题:

In my application i am parsing an xml file and validating the contents with xsd schema. When xml file gets bigger it takes some time to parse file and validate the contents. In this case I want visualize parsing and validation phases with progress bar. How to do this?

Note: I am using Qt with C++

回答1:

Basically you just create a QProgressDialog instance:

QProgressDialog progress("Parsing...", "Abort", 0, numOperations, this);
progress.setWindowModality(Qt::WindowModal);

where numOperations is the full number of things you need to do before the parsing is done. For this, you probably need to make a first quick pass through the data where you simply count the total number of elements to parse or something similar, and set this value as the maximum value numOperations in the previous example code. Then you make the actual processing pass and call setValue periodically:

progress.setValue(finishedOperations);

where finishedOperations is the number of things parsed so far.

This is assuming you want the simplest solution where the progress bar appears as a separate modal dialog. If you want to give the user the opportunity to abort the process, you need to implement a slot which you connect to the canceled() signal.

If you don't want the progress bar in a modal dialog, you just show a QProgressBar somewhere. It works in a similar way by calling setValue() periodically.



回答2:

Assuming that the xml parsing implementation is pulling its data from some sort of buffered stream attached to a file reader -- read the file size, then each time the the input buffer grabs another block from the file reader, update your progress indicator. This can probably be done most conveniently by deriving a new class from the file reader class and overriding the read block function to report progress.

The advantage of this approach is that it doesn't require you to do extra work for a pre-parse to estimate the number of operations, and can be used with any sort of streaming file processing scheme whether xml or any other format.



回答3:

what is the main looping structure of your algorithm?

if you are making a single pass through the document, you may not know when you are about to hit the end, in order to get a good progress meter, you may need to switch to a two pass implementation - which may be slower, but gives the feedback advantage.