6

我在 QML 中有一个代码片段,它应该在 screen.text 中查找正则表达式“Calling”,如果没有找到,那么它才会更改 screen.text。不幸的是,QML/QString文档中的文档不清楚.

  Button{
        id: call
        anchors.top: seven.bottom
        anchors.left: seven.left

        text: "Call"
        width: 40

        onClicked:{
            if(screen.text.toString().startsWith("Calling" , false))
                return;
            else
                screen.text = "Calling " + screen.text
        }
    }

我得到的错误是:

file:///home/arnab/workspace/desktop/examples/cellphone.qml:127: TypeError: 表达式'screen.text.toString().startsWith' [undefined] 的结果不是函数。

4

3 回答 3

6

您必须在处理程序中使用 Javascript 函数:

        onClicked:{
        var patt = /^Calling/;
        if(patt.test(screen.text))
            return;
        else
            screen.text = "Calling " + screen.text
    }
于 2011-07-13T12:23:59.810 回答
1

就像其他两个答案一样:toString()给出一个 JavaScript 字符串,而不是 a QString,并且 JavaScript 字符串没有 a startsWith()。使用显示的解决方法之一。

于 2011-07-13T15:42:05.350 回答
1

因为函数“startsWith”不是标准函数。

不能说您是否可以在 QML JS 中使用原型,但您使用以下代码:

String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}

或仅

if(screen.text.toString().match("^Calling")==screen.text.toString())

在这里阅读更多:http ://www.tek-tips.com/faqs.cfm?fid=6620

于 2011-07-13T12:21:35.500 回答