如何将自定义范围注入QML / Javascript控制台

时间:2015-08-14 11:50:28

标签: javascript qt qml qtquick2

我发现QML Book是学习QML的一个非常好的资源。我目前正在将他们建议的Javascript Console实施到我的QML应用程序中。但是我正在努力将控制台应用到我的应用程序范围内。

摘自QML书籍/第13页 - Javascript

// jsconsole.js
.pragma library

var scope = {
  // our custom scope injected into our function evaluation
  // <<--- How do I inject the "custom" scope? 
}

function call(msg) {
    var exp = msg.toString();
    console.log(exp)
    var data = {
        expression : msg
    }
    try {
        var fun = new Function('return (' + exp + ');');
        data.result = JSON.stringify(fun.call(scope), null, 2)
        console.log('scope: ' + JSON.stringify(scope, null, 2) + 'result: ' + result)
    } catch(e) {
        console.log(e.toString())
        data.error = e.toString();
    }
    return data;
}

如果这是一个小型QML应用程序:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2

ApplicationWindow {
    title: qsTr("Hello World")

    width: 640
    height: 480
    visible: true

    ListModel {
        id: contactsModel
        ListElement {
            name: "Bill Smith"
            position: "Engineer"
        }
        ListElement {
            name: "John Brown"
            position: "Engineer"
        }
        ListElement {
            name: "Sam Wise"
            position: "Manager"
        }
    }

    ListView{
        id: contactsView
        anchors.left: parent.left
        anchors.top: parent.top
        anchors.margins: 10
        width: parent.width
        height: parent.height
        orientation: Qt.Vertical
        spacing: 10
        model: contactsModel
        delegate: Rectangle{
            width: 150
            height: 30
            border.color: "black"
            border.width: 1
            Text{
                text: name
            }
        }
    }
}

我如何注入示例根组件或contactsModel作为自定义范围?

如果你能帮助我,我将不胜感激!

谢谢!

0 个答案:

没有答案