Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Python code from within PyQt event loop

I am testing a gui built using PyQt and I would like the ability to interact with the gui using python code that is executed after the PyQt event loop starts (app.exec_()). Another way of saying this is I would like the call to app.exec_ to return immediately as if the gui were modeless, followed by further python code which interacts with the gui.

I found this example of running the PyQt loop in a thread but don't want to do something so unconventional. Is there any way to get the PyQt message loop to continue processing messages while also executing python code in the main thread after exec_ has been called?

like image 535
Cerberellum Avatar asked Feb 04 '11 01:02

Cerberellum


2 Answers

One option here is to use a QtCore.QTimer.singleShot() call to start your python code after calling `exec_()'.

For example:

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    # Setup the GUI.    
    gui = MyGui()
    gui.showMainWindow()

    # Post a call to your python code.
    QtCore.QTimer.singleShot(1000, somePythonFunction)

    sys.exit(app.exec_()) 

This will execute the function somePythonFunction() after 1 second. You can set the time to zero to have the function added immediately queued for execution.

like image 123
amicitas Avatar answered Oct 14 '22 22:10

amicitas


As a possible easy answer, try not calling app.exec_() in your script and running your PyQt program using python -i My_PyQt_app.py.

For example:

## My_PyQt_app.py
import sys
from PyQt5.QtWidgets import QApplication, QWidget

app = QApplication(sys.argv)

window = QWidget()
window.show()

# Don't start the event loop as you would do normally!
# app.exec_()

Doing this should allow you to run the GUI through the terminal and interact with it in the command line.

like image 37
Chrisbm Avatar answered Oct 15 '22 00:10

Chrisbm