Search code examples
c++qtqmlqt5qtquick2

How to redirect qml's console.log() to cpp stdout


I am using qml( qtCreator ) and cpp (visual studio).

Usually the error messages are shown to the console, both from cpp and qml.

My requirement is that I should not have a console.

So I wrote a window application.

But when a flag has been set, I should launch a console. And show the corresponding error messages there.

I have used the following code in a function to set up this.

HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
int hCrt = _open_osfhandle((long) handle_out, _O_TEXT);
FILE* hf_out = _fdopen(hCrt, "w");
setvbuf(hf_out, NULL, _IONBF, 128);

// redirecting the buffers to the file handle
*stdout = *hf_out;
*stderr = *hf_out;

//attach std input to console
HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
hCrt = _open_osfhandle((long) handle_in, _O_TEXT);
FILE* hf_in = _fdopen(hCrt, "r");
setvbuf(hf_in, NULL, _IONBF, 128);
*stdin = *hf_in;

This will print the error log from stdout and stderr to a console.

To redirect qt error logs we can use.

How to redirect qDebug, qWarning, qCritical etc output?

But how do we redirect the output from console.log() of qml to the console.

Thanks in advance.


Solution

  • Here you can find a more verbose explanation.

    console.log is simply just qDebug, there is no difference to an end use. Your code should work, so I guess you just have not tested it properly. Although, your code seems to be strange because it is unnecessarily platform specific.

    Likely that you should get rid of that.

    By the way, Qt 4 was implementing something similar with QML viewer. Here you can find the code for an implementation example, in doubt.

    Hope, my reply answers your question. If not, please clarify.