Is there a way to use Qt without QApplication :: exec ()?

Is there a safe way to use Qt without calling QApplication :: exec ()?

I have several different objects that execute long-lived processes on several resources (at least one of them is connected to the web application server). I am making a GUI application that asks the user for input at the right time for these different processes. I would like my β€œflow” logic to be a logic that determines what to do next - in one place, and not in a GUI object, such as a dialog class. I thought I could do something like this:

... wait_dialog dlg; dlg.setModal( false ); dlg.show(); // Should return... netobject.start_long_lived_process_that_happens_on_other_thread( &completion_callback ); while ( !completion_callback_called() ) { qApp->processEvents(); netobject.pump_callbacks(); magically_avoid_busywait_while_still_servicing_qt_somehow(); } dlg.hide(); ... 

Is it safe from a Qt perspective? Is there a β€œgood” way to implement magically_avoid_busywait_while_still_servicing_qt_somehow() ?

What I'm trying to do here is to write our processing flow in the most explicit way. I need one function that does this:

  show_a_non_modal_wait_dialog() start_some_processing_1() wait_for_processing_1_to_finish() dismiss_non_modal_wait_dialog() show_modal_input_dialog() if ( cancelled ) return show_a_non_modal_wait_dialog() start_some_processing_2() wait_for_processing_2_to_finish() dismiss_non_modal_wait_dialog() show_modal_input_dialog() if ( cancelled ) return ... 

What I really want to avoid is starting and waiting for processing inside Qt widgets and windows. In addition, the processing objects themselves are completely independent of Qt. I suppose I'm trying to create a controller in one function with several helper callbacks and state variables.

+4
source share
1 answer

What you want is an event loop, the other is that of the main event of the application. This can be done using QEventLoop :

 wait_dialog dlg; dlg.setModal( false ); dlg.show(); // Should return... QEventLoop loop; connect(&netobject, SIGNAL(done()), &loop, SLOT(quit())); netobject.start_long_lived_process_that_happens_on_other_thread(); loop.exec(); // BLOCKING (non-busy) until quit() is called via the signal done() 

While this is (in my opinion) pure code, it requires your netobject class to be a QObject and implement the done() signal (which is also cleaner than providing callbacks).

Now you can wrap all this code in a function that will block the call by itself, so it can return some results from your dialog if you want to.

+5
source

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


All Articles