QRegExp and single-quoted text for QSyntaxHighlighter

前端 未结 1 668
一生所求
一生所求 2021-01-25 02:12

What would the QRegExp pattern be for capturing single quoted text for QSyntaxHighlighter? The matches should include the quotes, because I am building a sql code editor.

<
相关标签:
1条回答
  • 2021-01-25 02:31

    I am not an expert in regex but using a C++ answer to detect texts between double quotes changing it to single quote I see that it works:

    import sys
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class SyntaxHighlighter(QtGui.QSyntaxHighlighter):
        def __init__(self, parent=None):
            super(SyntaxHighlighter, self).__init__(parent)
    
            keywordFormat = QtGui.QTextCharFormat()
            keywordFormat.setForeground(QtCore.Qt.darkBlue)
            keywordFormat.setFontWeight(QtGui.QFont.Bold)
    
            keywordPatterns = ["'([^'']*)'"]
    
            self.highlightingRules = [(QtCore.QRegExp(pattern), keywordFormat)
                    for pattern in keywordPatterns]
    
        def highlightBlock(self, text):
            for pattern, _format in self.highlightingRules:
                expression = QtCore.QRegExp(pattern)
                index = expression.indexIn(text)
                while index >= 0:
                    length = expression.matchedLength()
                    self.setFormat(index, length, _format)
                    index = expression.indexIn(text, index + length)
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        editor = QtWidgets.QTextEdit()
        editor.append("string1 = 'test' and string2 = 'ajsijd'")
        highlighter = SyntaxHighlighter(editor.document())
        editor.show()
        sys.exit(app.exec_()) 
    

    0 讨论(0)
提交回复
热议问题