Skip to content

Magic window: run code on the Qt thread ​

PY → GUI · main thread

Controller methods do not run on the Qt main thread — a plain def runs on a worker pool and async def runs on the asyncio event loop. So you cannot call QMessageBox.information(...) or QLabel.setText(...) straight from a controller: Qt widgets may only be touched on the main thread.

AxonMagicGUI solves exactly that: it sends a function back to the main thread and returns the result as a Future. Call it from anywhere — a worker thread, the event loop, a timer.

Python side ​

controller.py
python
from PySide6.QtCore import class QThreadQThread
from PySide6.QtWidgets import class QApplicationQApplication, class QMessageBoxQMessageBox

from axon import AxonController(web_name: str | list[str] = '*', id: Optional[str] = None, shared: bool = False)
``AxonController`` 的命名空间对象:既能当装饰器用,也挂注册表操作。
AxonController
, class AxonMagicGUIAxonMagicGUI
@AxonController(web_name: str | list[str] = '*', id: Optional[str] = None, shared: bool = False)
``AxonController`` 的命名空间对象:既能当装饰器用,也挂注册表操作。
AxonController
("MainView")
class class DemoControllerDemoController: def ask(self) -> bool: def on_main() -> bool: # we are on the Qt main thread here: any widget is safe to use app = class QApplicationQApplication.instance() on_main_thread = class QThreadQThread.currentThread() is app.thread() class QMessageBoxQMessageBox.information(None, "From Python", "this dialog is opened on the main thread") return on_main_thread # run() returns a Future; .result(5) waits up to 5 seconds return class AxonMagicGUIAxonMagicGUI.run(on_main).result(5)
app.js
js
// the JS side calls it as usual and cannot tell the difference
const const onMainThread: anyonMainThread = await 
const Axon: {
    DemoController: {
        add(a: number, b: number): Promise<number>;
        asset_count(): Promise<number>;
        blob(size?: number): Promise<string>;
        broadcast(text: string): Promise<Array<any>>;
        call_js_mirror(payload: any): Promise<any>;
        cross_broadcast(text?: string): Promise<Record<string, any>>;
        cross_call(text?: string): Promise<any>;
        cross_close(): Promise<Array<string>>;
        cross_emit(text?: string): Promise<Array<string>>;
        cross_open(): Promise<Array<string>>;
        delayed(msg: string, ms?: number): Promise<string>;
        ... 13 more ...;
        counter: number;
    };
}

Axon 的 JS 侧语法糖。

ts
await Axon.Users.add(1, 2)          // 调 Python 方法, 位置参数直接摊开
await Axon.Users.slow([1000], {}, 300)  // 需要 kwargs / 超时时用打包写法
await Axon.Users.count              // 读 Python 属性 (getVar)
Axon.Users.count = 3                // 写 Python 属性 (setVar, fire-and-forget)

属性读是惰性的: 只有真正 await / .then / .catch / .finally 时才发请求。 取到的 dispatcher 本身是函数, 同时挂了 then/catch/finally, 让 Axon.Users.count 既能当 Promise 用, 又能当方法调用。

Axon
.
type DemoController: {
    add(a: number, b: number): Promise<number>;
    asset_count(): Promise<number>;
    blob(size?: number): Promise<string>;
    broadcast(text: string): Promise<Array<any>>;
    call_js_mirror(payload: any): Promise<any>;
    cross_broadcast(text?: string): Promise<Record<string, any>>;
    cross_call(text?: string): Promise<any>;
    cross_close(): Promise<Array<string>>;
    cross_emit(text?: string): Promise<Array<string>>;
    cross_open(): Promise<Array<string>>;
    delayed(msg: string, ms?: number): Promise<string>;
    fail(reason?: string): Promise<null>;
    ... 12 more ...;
    counter: number;
}
DemoController
.ask();

Initialise it first

After creating QApplication, call AxonMagicGUI() once — otherwise run() raises RuntimeError("init AxonMagicGUI first"):

main.py
app = QApplication(sys.argv)
AxonMagicGUI()                 # once is enough
view = AxonGUI("MainView", url)

Key points ​

  • Only use it when a Qt object is involved: pure computation, file IO or HTTP requests do not need the main thread.
  • run() queues asynchronously: the function goes into the main thread's event queue and the result comes back through a Future; you may ignore the result, but do not expect it to run "immediately".
  • Do not block inside on_main: time.sleep or a synchronous request freezes the whole UI — that code runs on the main thread.
  • Awaiting it from async def: await asyncio.wrap_future(AxonMagicGUI.run(on_main)).

Related

To send one call to every window, use broadcast.