Cerberellum
Cerberellum

Reputation: 71

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?

Upvotes: 7

Views: 7796

Answers (5)

Chrisbm
Chrisbm

Reputation: 11

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.

Upvotes: 1

tyrion
tyrion

Reputation: 2303

The easiest way is to use IPython:

ipython --gui=qt4

See ipython --help or the online documentation for more options (e.g. gtk, tk, etc).

Upvotes: 0

amicitas
amicitas

Reputation: 13651

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.

Upvotes: 2

Drake Guan
Drake Guan

Reputation: 15122

Not exactly sure what you wanna do. Are you looking for something like Py(known as PyCrust) for PyQt?

Upvotes: 0

Cerberellum
Cerberellum

Reputation: 1

I got it. I can execute the test script line-by-line from the main thread using exec and then run the gui from a worker thread.

Upvotes: 0

Related Questions