[Interest] Relationship between a QEventLoop and QCoreApplication::exec().
Konrad Rosenbaum
konrad at silmor.de
Mon Aug 8 08:25:04 CEST 2016
Hi,
On Sunday 07 August 2016 10:06:54 Thiago Macieira wrote:
> On domingo, 7 de agosto de 2016 10:17:44 PDT André Somers wrote:
> > > Yet, I don't see where the problem is. QDialog::exec() displays a
> > > modal
> > > dialog. It is not possible to click again on the menu or button that
> > > displayed the dialog in the first place. It effectively breaks
> > > recursive
> > > looping, right?
> >
> > Wrong. There are many sources of events, and only the ones related to
> > user input are blocked this way.
>
> Indeed. Think of your sockets, that are still receiving data and that is
> being processed. Are you sure that your dialog wasn't created as a
> response to some data being processed earlier?
>
> Think also of all the timers that will time out.
Let me weigh in at this point: yes, it is true - nested event loops make it
very easy to shoot yourself in the foot. Sorry, you are using C++, if you
wanted it safe you would bake bread.
I use them all the time because they make simple algorithms understandable -
event based constructs, even using lambdas, make them horribly hard to
understand. I even wrote a few such methods for my own code.
Here's the choice:
a) avoid exec() at all costs and suffer unreadable code and a lot of the
problems described below simply get hidden in a forest of less readable code
b) follow a few simple rules instead:
- avoid direct delete on QObjects - use deleteLater instead (it is delayed
for the main event loop)
- use high-level methods instead of deletes: e.g. tell a window to close
itself and set it up for automatic cleanup instead of deleting it directly
- try to communicate via signals and set the connections up when you create
the receiver object - Qt will clean the connections up when the receiver is
deleted
- if you absolutely and positively cannot avoid using a pointer - use
QPointer and check it before you call a method
- enable your code to deal with disappearing objects - i.e. let a child
object tell its parent that it is gone and stop any actions that depend on
it when you receive this signal (otherwise you risk endless waiting)
- when you write code that can take a while: think about everything that
could conceivably happen in between and prepare the program for "stuff
happening" - i.e. disappearing objects, more events coming in, things
queuing up, the user losing patience and clicking "Exit", etc.
Qt make it very easy for you to write readable code - I refuse to compromise
this out of paranoia.
Konrad
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 473 bytes
Desc: This is a digitally signed message part.
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20160808/ef643fbf/attachment.sig>
More information about the Interest
mailing list