c++qtqtscript

QtScript output redirection


When I call this code:

QScriptEngine e;
e.evaluate("print('hello, world!')");

the output text (from print method) is written to main application's terminal.

Is there any way to redirect it to a custom QIODevice?


Solution

  • You can replace print() with your own implementation:

    First, define a C++ function that does what you want. In this case, it's just empty for exposition:

    QScriptValue myPrint( QScriptContext * ctx, QScriptEngine * eng ) {
        return QScriptValue();
    }
    

    Then install that function as your new print():

    QScriptEngine e = ...;
    e.globalObject().setProperty( "print", e.newFunction( &myPrint ) );
    e.evaluate( "print(21);" ); // prints nothing