QT Progress bar showing status of a function

2019-07-21 21:10发布

recently I'm working on Point cloud Library project with QT. I'd like to know if I can know the current progress when I use a function.

For example, I create a class name system with a public function named estimate_normal. Inside this estimate_normal, I call some functions from the PCL library, and in MainWindow.cpp I call

system a;
a.estimate_normal();

Can I know the progress by using QT Progress bar to see this estimate_normal status?

Thanks

1条回答
劳资没心,怎么记你
2楼-- · 2019-07-21 21:53

You should create your object of the class "system" on the heap and move it to a new thread in order to prevent estimate_normal() from blocking main thread and the UI. This can be done like:

a = new system();
QThread * th = new QThread();
a->moveToThread(th);

QObject::connect(th,SIGNAL(started()),a,SLOT(OnStarted()));
QObject::connect(th,SIGNAL(finished()),a,SLOT(OnFinished()));

th->start();

Your initialization and termination tasks in the class "system" should be done in OnStarted() and OnFinished() slots respectively.

You should use a signal in the class "system" to notify the progress bar in your user interface of the value for the progress. In your estimate_normal() function you should emit the signal with the appropriate value. The signal is like:

void progressChanged(int val);

You should also connect the progressChanged(int) signal to the setValue(int value) slot of the QProgressBar.

And the last point is that you should not call estimate_normal() directly when it is in an other thread. The correct way is defining estimate_normal() as a slot and connecting a signal to that slot and emitting the signal when you want to call estimate_normal().

查看更多
登录 后发表回答