Qt Time-consuming programming and computing

I am new to Qt programming. I have to do some calculations that take a lot of time. I use the edit box and two buttons with the name "start" and "stop". An initialization field is used for initialization. The start button starts the calculation. While the calculation is going on, I should be able to stop the calculation whenever I want. But when I start the calculation, click the "Start" button. As expected, I cannot click on any component of the window until the calculation is complete.

I want to use components (especially the stop button) in the window when the calculation is performed. But I'm not very good at threads, I'm looking for a simpler method. Is there a simple solution?

+4
source share
4 answers

Either use streams (possibly by synchronizing them, sending messages to channels for yourself), or use timer (with 0 millisecond delays, this is how idle processing is performed in Qt).

0
source

There are several options.

1. Subclass QRunnable

Subclass QRunnable and use QThreadPool to run it in a separate thread. Use signals to communicate with the user interface. An example of this:

class LongTask: public QRunnable { void run() { // long running task } }; QThreadPool::globalInstance()->start(new LongTask); 

Please note that you do not need to worry about controlling the flow or lifetime of your QRunnable. For communication, you can connect your custom signals before starting QRunnable.

2. Use QtConcurrent :: run

This is a different approach and may not suit your problem. Basically, the way it works is this: you get a handle to the future return value of a long task. When you try to restore the return value , it will either immediately send it to you, or wait for the task to complete if it has not already been completed. Example:

 QFuture<int> future = QtConcurrent::run(longProcessing, param1, param2); // later, perhaps in a different function: int result = future.result(); 

3. Subclass QThread

You probably do not need this, but it is also not difficult. This is very similar to # 1, but you need to control the flow yourself. Example:

 class MyThread : public QThread { public: void run() { // long running task } }; QThread* thread = new MyThread(this); // this might be your UI or something in the QObject tree for easier resource management thread.start(); 

Similar to QRunnable, you can use signals to communicate with the user interface.

+16
source

In your calculations, you can put QCoreApplication::processEvents(); so that GUI events are also handled. This will omit the use of threads.

+3
source

You can have your calculations in a thread other than your GUI. When the GUI receives a signal that the stop button has been pressed, you change the flag value, which periodically checks the flow of calculations. When the flag is set, you can complete the flow of calculations.

+1
source

Source: https://habr.com/ru/post/1383493/


All Articles