示例#1
0
class MacroHighlighter(QSyntaxHighlighter):
    def __init__(self,textboxdoc,valid_list_of_commands):
        QSyntaxHighlighter.__init__(self,textboxdoc)
        self.valid_syntax="|".join([command.regexp_str for command in valid_list_of_commands])
        self.my_expression = QRegExp(self.valid_syntax)
        #define a blue font format for valid commands
        self.valid = QTextCharFormat()
        self.valid.setForeground(Qt.black)
        #define a bold red font format for invalid commands
        self.invalid = QTextCharFormat()
        self.invalid.setFontWeight(QFont.Bold)
        self.invalid.setForeground(Qt.red)
        #define a blue font format for valid parameters
        self.valid_value=QTextCharFormat()        
        self.valid_value.setFontWeight(QFont.Bold)
        #self.valid_value.setForeground(QColor.fromRgb(255,85,0))
        self.valid_value.setForeground(Qt.blue)
                
    def highlightBlock(self, text):
        #this function is automatically called when some text is changed
        #in the texbox. 'text' is the line of text where the change occured    
        #check if the line of text contains a valid command
        match = self.my_expression.exactMatch(text)
        if match:
            #valid command found: highlight the command in blue
            self.setFormat(0, len(text), self.valid)
            #highlight the parameters in orange
            #loop on all the parameters that can be captured
            for i in range(self.my_expression.captureCount()):
                #if a parameter was captured, it's position in the text will be >=0 and its capture contains some value 'xxx'
                #otherwise its position is -1 and its capture contains an empty string ''
                if self.my_expression.pos(i+1)!=-1:
                    self.setFormat(self.my_expression.pos(i+1), len(self.my_expression.cap(i+1)), self.valid_value)
        else:
            #no valid command found: highlight in red
            self.setFormat(0, len(text), self.invalid)