我目前正在基于PyQt5的应用程序上工作,我可以使用(嵌入式)编辑器为其提供一些针对YAML(可能是JSON)的语法突出显示。

我希望Qt对此具有一些内置功能,但是我发现的只是一些讨论和一些手工实现,例如this one

没有一种简单的方法来激活现有窗口小部件上的语法突出显示吗?还是我可能会使用的紧凑型第三方小部件?

最佳答案

您可以将QsciScintilla类与QsciLexerJSON模块的QsciLexerYAMLQScintilla词法分析器一起使用。

import sys, os
from PyQt5 import QtWidgets, Qsci

JSON = """
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}
"""

YAML = """
--- !clarkevans.com/^invoice
invoice: 34843
date   : 2001-01-23
bill-to: &id001
    given  : Chris
    family : Dumars
    address:
        lines: |
            458 Walkman Dr.
            Suite #292
        city    : Royal Oak
        state   : MI
        postal  : 48046
ship-to: *id001
product:
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
    - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.52
comments: >
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338.
"""


class JSONEditor(Qsci.QsciScintilla):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setLexer(Qsci.QsciLexerJSON(self))
        self.setText(JSON)


class YAMLEditor(Qsci.QsciScintilla):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setLexer(Qsci.QsciLexerYAML(self))
        self.setText(YAML)


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QWidget()
    lay = QtWidgets.QHBoxLayout(w)
    lay.addWidget(JSONEditor())
    lay.addWidget(YAMLEditor())
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())


python - PyQt5的语法突出显示编辑器-LMLPHP

07-23 00:59