Menu

Using QSyntaxHighlighter from Python

Help
2016-04-11
2016-06-19
  • Brad Elliott

    Brad Elliott - 2016-04-11

    Is it possible to use QSyntaxHighlighter from Python? I've tried subclassing QSyntaxHighlighter but I can't figure out how to deal with the highlightBlock method which is a pure virtual method inside QSyntaxHighlighter. This method needs to be implemented in the derived class. It seems like PythonQt created a placeholder for this function but I'm not sure if I can replace it or if I have to implement the highlighter in C++.

     
  • Brad Elliott

    Brad Elliott - 2016-04-11

    I tried the code below but it doesn't seem to call the highlightBlock() method:

    class mySyntaxHighlighter(qt.QSyntaxHighlighter):
    
        def __init__(self, document):
            qt.QSyntaxHighlighter.__init__(self, document)
    
        def highlightBlock(self, text):
    
     
  • Florian Link

    Florian Link - 2016-04-12

    I found the problem... The constructor of QSyntaxHighlighter has three overloads and PythonQt chooses the first one, which is QObject. So the solution is to do an extra setDocument() call.

    The following works for me:

    class mySyntaxHighlighter(QtGui.QSyntaxHighlighter):
    
        def __init__(self, document):
            QtGui.QSyntaxHighlighter.__init__(self, document)
            self._fmt = QtGui.QTextCharFormat()
            self._fmt.setFontItalic(True)
    
        def highlightBlock(self, text):
          self.setFormat(0,2, self._fmt)
    
    b = QtGui.QTextEdit()
    hi = mySyntaxHighlighter(b)
    hi.setDocument(b.document())
    b.setText("test\ntest\ntest\n")
    b.show()  
    
     
  • Brad Elliott

    Brad Elliott - 2016-06-19

    Sorry, I forgot to reply to this. Your solution did work! Thanks for your help. Your project is awesome.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.