views:

326

answers:

2

I'm facing a practical problem with Qt. I'm using a class that communicates with QLocalSocket to another process (pipes/unix sockets) and I need to do that communication before other events occur, that is before app.exec() starts (or more precisely,as soon as app starts). The class that I'm using needs an eventloop so it does not work if I call the class methods before an event loop is started. There is any way to start something when the event loop is ready? I thought of making a hidden event-only window and do my duties in the hidden window constructor, and stablish this window as toplevel.

Basically, I need this local-socket communication task to start as soon as the event loop becomes available.

Any ideas?

Thank you.

+4  A: 

You could start a separate eventloop, using QEventLoop, before calling QApplication::exec(). You should emit a "done" signal from your class and connect that to the QEventLoop quit() slot, or use an existing signal provided in the Qt class you're using.

Here's a simple example fetching a webpage using QNetworkAccessManager:

app = QtCore.QCoreApplication([])
manager = QtNetwork.QNetworkAccessManager()
req = QtNetwork.QNetworkRequest(QtCore.QUrl("http://www.google.com"))
resp = manager.get(req)
eventloop = QtCore.QEventLoop()
eventloop.connect(resp, QtCore.SIGNAL('finished()'), QtCore.SLOT('quit()'))

eventloop.exec_() # this will block until resp emits finished()

print resp.readAll()

app.exec_()

While this might suit your needs, I couldn't quite understand why you can't simply do whatever business you have prior to calling show() on your window, once that's done, call show().

Idan K
I forgot to mention this is a non-UI process, it's a listener process.
Hernán
I see, well try the QEventLoop, it will work with a non-UI app aswell.
Idan K
+1  A: 

If you just need to start the communications before everything else, you can simply use a single-shot timer with 0ms delay:

QTimer::singleShot(0, commsInstancePtr, SLOT(startCommunication()));

If you need your operations to actually finish before doing everything else, Daniel's solution might be more suitable.

frgtn
Your solution may fit as well, since I can disable normal processing until I get the local IPC done. Thank you.
Hernán