尽管globalObject在QQmlEngine中是只读的,但其中存储的值不是。所以你可以修改globalObject的控制台属性。你可以在 C++ 和 QML 中做到这一点。这是 QML 中一个简单的运行示例:
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Console example")
Column {
anchors.centerIn: parent
Button {
text: "debug"
onClicked: {
console.log = console.debug
}
}
Button {
text: "exception"
onClicked: {
console.log = console.exception
}
}
Button {
text: "print something"
onClicked: {
console.log( "logging something" );
}
}
}
}
前两个按钮发生变化,第三个按钮的作用是通过修改console.log方法。C++ 看起来像这样(我不能在这里复制我的所有代码,抱歉,但它应该能让你继续前进,而且效果很好):
// in a header file
class HelperObject: public QObject {
Q_OBJECT
// ...
public slots:
myLog( QString aMessage );
};
// in an implementation file
QQmlEngine qmlEngine;
HelperObject helperObject;
QJSValue helperValue = qmlEngine.newQObject( &helperObject );
QJSValue consoleObject( qmlEngine.globalObject().property( "console" ) );
if (!consoleObject.isUndefined()) {
QJSValue myLogValue = helperValue.property( "myLog" );
consoleObject.setProperty( "log", myLogValue );
}