9. Application
The classes and methods in this sub-module are essential for interacting with the graphical user interface (GUI) in STKO. They enable you to identify GUI components, such as the Work Tree, Terminal, Editor, or Script in PyMpc (MpcGUIComponents). Additionally, they facilitate interaction with the working thread, definition of a new thread providing access to documents, and creation of a process monitor.
The App sub-module allows you to create and run utilities and custom commands.
The main class in this sub-module is the MpcBackgroundWorkerProgressMonitorInterface
,
which is a monitor interface that enables dialogue with a process running on a separate thread.
You can interact with threads using various functions, such as:
runCommand
: a utility to run a specific commandprocessEvents
: to process all events in the event loop that were waiting while a previous process was runningcurrentSolverName
: to query the name of the solver in useclearTerminal
: to clear the terminal windowupdateActiveView
: to update the render view
The following example demonstrates how to create a simple function that defines a pop-up window to monitor a process running on the working thread. This window displays the number of iterations and the percentage complete.
from PyMpc.App import (runOnBlockingWorkingThread,monitor)
from time import sleep
from PySide2.QtCore import QThread
def function():
print("From WORKER: ", QThread.currentThread())
m = monitor()
for i in range(10):
sleep(0.5)
m.sendMessage('iteration {}'.format(i+1))
m.sendPercentage(float(i+1)/10.0)
print("From GUI: ", QThread.currentThread())
runOnBlockingWorkingThread(function)
You can complement this function with another one that interrupts the process on the working thread and asks for user input to continue. Before defining the function to run in the working thread, use QApplication to get the active window, make the counter global, and set the range for the current call.
from PyMpc.App import (runOnBlockingWorkingThread,monitor)
from time import sleep
from PySide2.QtCore import (QThread)
from PySide2.QtWidgets import (QApplication,QMessageBox)
awin = QApplication.activeWindow()
counter = 0
rstart, rend = 0, 0
def function():
global counter
try:
m = monitor()
for i in range(rstart, rend):
sleep(0.5)
counter += 1
m.sendMessage('iteration {}'.format(counter))
m.sendPercentage(float(i+1)/10.0)
except Exception as ex:
print(ex)
This time, the function is called with the runOnBlockingWorkingThread of PyMpc.App inside another function that first runs part of the process, then interrupts it at a specified threshold to query the user, and finally completes it.
def main_function():
global rstart, rend
rstart, rend = 0, 5
runOnBlockingWorkingThread(function)
if QMessageBox.information(awin, "STKO Script Example", "Done 50% of the job, do you want to continue?", QMessageBox.Yes | QMessageBox.Cancel) != QMessageBox.Yes:
return
rstart, rend = 5, 10
runOnBlockingWorkingThread(function)
main_function()