开发者

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?


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,...)-

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜