I would like to execute a method which can only be called once my QApplication
is displayed, i.e. when it has entered its main event loop exec_()
. I'm new to Qt4 (using PyQt4): i was hoping to have a on_start()
-like callback, but didn't find one.
Do i need to create a thread or a timer? Or is there some callback included in the API already?
For now i have chosen to use QThread
this way:
class MyThread(QtCore.QThread):
def run(self):
''' reinplemented from parent '''
# make thread sleep to make sure
# QApplication is running before doing something
self.sleep(2)
do_something()
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.attr = 'foo'
self.thread = MyThread(self)
self.thread.start()
def main():
app = QtGui.QApplication(sys.argv)
w = MyWidget()
w.show()
sys.exit(app.exec_())
It works for my purpose because my thread in my (real) code actually looks for the application window in X display and will try doing so until it finds it. But otherwise that's not an elegant way to solve the problem.
It would be nicer if there was a signal emitted by QApplication
when entering the event-loop. JAB proposed the Qt.ApplicationActivate but it doesn't seem to be emitted by QApplication
, and even if it was, because the MyWidget()
is not instantiated as a child of QApplication
, i wouldn't know how to pass the signal from app
to w
I'll wait for a better answer, if any, before accepting my answer as the chosen solution.