开发者

Qt QML How to format (highlight) text

开发者 https://www.devze.com 2023-04-01 11:02 出处:网络
I would like to write a simple plain text editor including simple markdown instructions in QML. Therefore I added a TextEdit-Element and a JavaScript Function for Syntax Highlighting.

I would like to write a simple plain text editor including simple markdown instructions in QML. Therefore I added a TextEdit-Element and a JavaScript Function for Syntax Highlighting.

As an example:

I want to print the string between two 开发者_开发问答asterisks '*' in bold.

So I have to insert a <b> tag before or a </b> tag after the latest symbol (*), but the property of the element is a HTML document.

How can I find the right position (I can access the cursor position but this is different to the html-doc position)? And insert these tags? Are there some helper methods, cheats or guidelines?


You can use window.getSelection() for get the selected text.

For example:

HTML:

<div id="test" onmouseover="getSelectedText()">a*b*</div>

JavaScript:

function getSelectedText() {
            var m = 'getSelection';
            if(m in window) {
              var Selection =  new String(window[m]());
              var text =  multiReplace([/\*([^*]+)\*/], 
                                        [RegExp.$1.bold()],
                                         Selection
                                        );

               alert(text);
            }
  }


function multiReplace(arr1,arr2,str) {
    if(arr1 instanceof Array) {
        for(var i = 0,len = arr1.length; i < len; i++) {
            str = str.replace(arr1[i],arr2[i]);
        }
    } else if(arr1 instanceof Object) {
        str = arr2;
        for(var key in arr1) {
            str = str.replace(key, arr1[key]);
        }
    } else {
        return null;
    }
        return str;
}
0

精彩评论

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