Home > front end >  Is it possible to highlight text as the user types?
Is it possible to highlight text as the user types?

Time:09-22

I'm trying to create an input box that highlights text as the user writes it.

patients = ["AB", "GH", "JS", "LP"]
attributes = ["medication", "weight", "mobility"]
commands = ["get" , "add", "replace", "delete"]

I'd like it to format each type of word differently e.g.

AB add medication aspirin' -> 'AB add MEDICATION "aspirin"'

JS get medication -> JS get MEDICATION

Is this possible? I'm not necessirilly looking for the code which would pull it off; I'd just like to know if it's doable before I commit serious time to working on it.

CodePudding user response:

Yes, it's possible, but only for input widgets based on QTextDocument, such as QPlainTextEdit or QTextEdit, as the basic one-line widget QLineEdit doesn't support formatting.

You need to create a subclass of QSyntaxHighlighter and override its highlightBlock() function, then cycle through all groups, create a valid regex and provide the relative format:

def highlightBlock(self, text):
    fmt = QtGui.QTextCharFormat()
    fmt.setFontWeight(QtGui.QFont.Bold)
    patientList = '|'.join('({})'.format(v) for v in patients)
    patientRegEx = QtCore.QRegularExpression(
        r'\b({})\b'.format(patientList)
        )
    rxIter = QtCore.QRegularExpressionMatchIterator(
        patientRegEx.globalMatch(text))
    while rxIter.hasNext():
        match = rxIter.next()
        self.setFormat(
            match.capturedStart(), 
            match.capturedLength(), 
            fmt)

Then set the highlighter on the document for the text edit:

    self.inputField = QTextEdit()
    self.highlighter = MySyntaxHighlighter(self.inputField.document())

Note that it seems that there's a known and unresolved bug in the syntax highlighter, so setting the font capitalization will not work.

Unfortunately there's no easy workaround for this, so you need to find other ways to highlight the attributes.

To know the options available for character formats, see the documentation for QTextCharFormat and also QTextFormat (from which it inherits), which also provides useful functions like setBackground and setForeground.

  • Related