Autocompletion using PyQt4 and QScintilla

I’m currently toying with the idea of creating a specialised code editor for questionnaires in Python using PyQt4. One of the best plugins for Qt for this job is QScintilla, a wrapper around Scintilla – an open source editing component. Scintilla to its credit has a huge amount of great features, including code-folding, syntax highlighting and auto-completion of words. But the documentation can be a little lacking at times, and there aren’t a whole lot of examples on how to use some of the features.

The one feature, that I was trying to implement was auto-completion, but I had no luck finding python examples that demonstrated everything you needed to get it working. So, after some searching, some hacking, some crying and then finally some reading for the documentation, I came up with the following minimal example with auto-completion in a basic editor:

#!/usr/bin/env python
# -*- coding: latin1 -*-
 
"""
Basic use of the QScintilla2 widget
 
Note : name this file "qt4_sci_ac_test.py"
Base code originally from: http://kib2.free.fr/tutos/PyQt4/QScintilla2.html
"""
 
import sys
from PyQt4.QtGui import QApplication
from PyQt4 import QtCore, QtGui, Qsci
from PyQt4.Qsci import QsciScintilla, QsciScintillaBase, QsciLexerPython
 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    editor = QsciScintilla()
 
    ## Choose a lexer
    ## This can be any Scintilla lexer, but the original example used Python
    lexer = QsciLexerPython()
 
    ## Create an API for us to populate with our autocomplete terms
    api = Qsci.QsciAPIs(lexer)
    ## Add autocompletion strings
    api.add("aLongString")
    api.add("aLongerString")
    api.add("aDifferentString")
    api.add("sOmethingElse")
    ## Compile the api for use in the lexer
    api.prepare()
 
    editor.setLexer(lexer)
 
    ## Set the length of the string before the editor tries to autocomplete
    ## In practise this would be higher than 1
    ## But its set lower here to make the autocompletion more obvious
    editor.setAutoCompletionThreshold(1)
    ## Tell the editor we are using a QsciAPI for the autocompletion
    editor.setAutoCompletionSource(QsciScintilla.AcsAPIs)
 
    ## Render on screen
    editor.show()
 
    ## Show this file in the editor
    editor.setText(open("qt4_sci_ac_test.py").read())
    sys.exit(app.exec_())

Thanks to Kib2 and his example on code for QScintilla2 that this example is based on.

Comment are closed.