Qt5语法在QML中突出显示

Ita*_*dev 16 syntax-highlighting qml qt5 qtquick2

我正在进行QtQuick 2.0演示,我想嵌入一些代码示例.是否可以轻松创建突出显示qml元素的语法.

您能否举例说明如何实现它的示例技术和想法.

谢谢

seb*_*sgo 8

在QML中没有明显的方法来实现语法高亮.

可以实现一个自己的声明项,执行实际的突出显示, QSyntaxHighlighter但是必须为所讨论的源代码的语言定义自己的突出显示规则.我不会为演示文稿做那么多的编码.

相反,我会在WebView项目中显示代码,突出显示已经应用为静态HTML标记,或者在JavaScript高亮库的帮助下,用于expample highlight.js.

更新1

如果该WebView项目确实无法使用,即使是Text具有基本HTML支持的简单项目也足以处理突出显示用例的源代码(如果使用静态HTML).


Jam*_*ner 8

Qt Quick的TextEdit项目公开了一个textDocument类型的属性QQuickTextDocument.这是明确公开的,因此您可以QSyntaxHighlighter直接使用该文档.

QtQuick用于Qt 5.3的textEdit文档


Ste*_*uan 7

我有两个答案:

  1. 一个纯粹的 QML 答案
  2. 涉及 QSyntaxHighlighter 的 C++ 答案

对于纯 QML 答案,我们可以使用TextAreaone can usetextFormat: TextEdit.RichText进行格式化。我们可以使用TextArea::getText()获取纯文本并设置TextArea::text为富文本。这是一个模拟示例:

  • 颜色大写标识符(例如按钮)为紫色
  • 颜色小写标识符(例如 xyz)为红色
  • 颜色编号(例如 123 456)为蓝色
  • 但将符号(例如 = + ;)保留为黑色

这是片段:

    TextArea {
        id: output

        property bool processing: false

        text: "<p>x = 123;</p><p>y = 456;</p><p>z = x + y;</p>"
        textFormat: TextEdit.RichText
        selectByMouse: true

        onTextChanged: {
            if (!processing) {
                processing = true;
                let p = cursorPosition;
                let markUp = getText(0, length).replace(
                  /([A-Z][A-Za-z]*|[a-z][A-Za-z]*|[0-9]+|[ \t\n]|['][^']*[']|[^A-Za-z0-9\t\n ])/g,
                    function (f) {
                        console.log("f: ", JSON.stringify(f));
                        if (f.match(/^[A-Z][A-Za-z]*$/))
                            return "<span style='color:#800080'>" + f + "</span>";
                        if (f.match(/^[a-z][A-Za-z]*$/))
                            return "<span style='color:#800000'>" + f + "</span>";
                        else if (f.match(/^[0-9]+$/))
                            return "<span style='color:#0000ff'>" + f + "</span>";
                        else if (f.match(/^[ ]/))
                            return "&nbsp;"
                        else if (f.match(/^[\t\n]/))
                            return f;
                        else if (f.match(/^[']/))
                            return "<span style='color:#008000'>" + f + "</span>";
                        else
                            return f;
                    }
                );
                text = markUp;
                cursorPosition = p;
                processing = false;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

要使用 Qt 的 QSyntaxHighlighter,您需要以下内容:

  1. 在 QML 中,在您的应用程序中使用 TextEdit QML 类型
  2. 在 C++ 中,定义一个 QSyntaxHighlighter 并通过 textDocument 属性将 TextEdit QML 类型连接到它
  3. 在 C++ 中,QSyntaxHighlighter::highlightBlock( const QString& text )在派生类中实现,setFormat()根据需要经常调用以标记找到的文本。

为了让事情变得更简单,我创建了一个示例应用程序https://github.com/stephenquan/QtSyntaxHighlighterApp,它包含QSyntaxHighlighterQTextFormat作为SyntaxHighlighterTextFormatQML 类型。这样,就可以处理 onHighlightBlock 信号并将语法高亮器的业务逻辑放在 Javascript 而不是 C++ 中:

TextEdit {
    id: textEdit
    selectByMouse: true
    text: [
        "import QtQuick 2.12",
        "",
        "Item {",
        "    Rectangle {",
        "        width: 50",
        "        height: 50",
        "        color: '#800000'",
        "    }",
        "}",
    ].join("\n") + "\n"
    font.pointSize: 12
}

SyntaxHighlighter {
    id: syntaxHighlighter
    textDocument: textEdit.textDocument
    onHighlightBlock: {
        let rx = /\/\/.*|[A-Za-z.]+(\s*:)?|\d+(.\d*)?|'[^']*?'|"[^"]*?"/g;
        let m;
        while ( ( m = rx.exec(text) ) !== null ) {
            if (m[0].match(/^\/\/.*/)) {
                setFormat(m.index, m[0].length, commentFormat);
                continue;
            }
            if (m[0].match(/^[a-z][A-Za-z.]*\s*:/)) {
                setFormat(m.index, m[0].match(/^[a-z][A-Za-z.]*/)[0].length, propertyFormat);
                continue;
            }
            if (m[0].match(/^[a-z]/)) {
                let keywords = [ 'import', 'function', 'bool', 'var',
                                'int', 'string', 'let', 'const', 'property',
                                'if', 'continue', 'for', 'break', 'while',
                    ];
                if (keywords.includes(m[0])) {
                    setFormat(m.index, m[0].length, keywordFormat);
                    continue;
                }
                continue;
            }
            if (m[0].match(/^[A-Z]/)) {
                setFormat(m.index, m[0].length, componentFormat);
                continue;
            }
            if (m[0].match(/^\d/)) {
                setFormat(m.index, m[0].length, numberFormat);
                continue;
            }
            if (m[0].match(/^'/)) {
                setFormat(m.index, m[0].length, stringFormat);
                continue;
            }
            if (m[0].match(/^"/)) {
                setFormat(m.index, m[0].length, stringFormat);
                continue;
            }
        }
    }
}

TextCharFormat { id: keywordFormat; foreground: "#808000" }
TextCharFormat { id: componentFormat; foreground: "#aa00aa"; font.pointSize: 12; font.bold: true; font.italic: true }
TextCharFormat { id: numberFormat; foreground: "#0055af" }
TextCharFormat { id: propertyFormat; foreground: "#800000" }
TextCharFormat { id: stringFormat; foreground: "green" }
TextCharFormat { id: commentFormat; foreground: "green" }
Run Code Online (Sandbox Code Playgroud)


Ber*_*and 5

在您的应用文件中:

QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QQuickTextDocument* doc = childObject<QQuickTextDocument*>(engine, "textEditor", "textDocument");
Q_ASSERT(doc != 0);

// QSyntaxHighlighter derrived class
MySyntaxHighlighter* parser = new MySyntaxHighlighter(doc->textDocument());
// use parser, see QSyntaxHighlighter doc...
int ret = app.exec();
delete parser;
return ret;
Run Code Online (Sandbox Code Playgroud)

获取子对象的模板函数(返回第一次出现的objectName,因此请使用唯一的名称来标识qml文件中的对象):

template <class T> T childObject(QQmlApplicationEngine& engine,
                                 const QString& objectName,
                                 const QString& propertyName)
{
    QList<QObject*> rootObjects = engine.rootObjects();
    foreach (QObject* object, rootObjects)
    {
        QObject* child = object->findChild<QObject*>(objectName);
        if (child != 0)
        {
            std::string s = propertyName.toStdString();
            QObject* object = child->property(s.c_str()).value<QObject*>();
            Q_ASSERT(object != 0);
            T prop = dynamic_cast<T>(object);
            Q_ASSERT(prop != 0);
            return prop;
        }
    }
    return (T) 0;
}
Run Code Online (Sandbox Code Playgroud)

在您的qml文件中,使用TextEdit(在Flickable或您想要的任何东西内部),并正确设置objectName属性:

.... 
TextEdit {
    id: edit
    objectName: "textEditor"
    width: flick.width
    height: flick.height
    focus: true
    font.family: "Courier New"
    font.pointSize: 12
    wrapMode: TextEdit.NoWrap
    onCursorRectangleChanged: flick.ensureVisible(cursorRectangle)
}
....
Run Code Online (Sandbox Code Playgroud)