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?
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
The output text goes to stdout, so you need to redirect stdout. For ideas see this question. Best ideas: use reopen to redirect to a FILE*, or (better) use rdbuf to redirect stdout to some other stream derived from std::ostream, and you could play with QFile.open(1,...)-
精彩评论