Qt4.5: Using event-loop based localsocket before app.exec

冷暖自知 提交于 2019-12-07 13:28:23

问题


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.


回答1:


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().




回答2:


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.



来源:https://stackoverflow.com/questions/1754256/qt4-5-using-event-loop-based-localsocket-before-app-exec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!