Issue
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.
Solution
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
.
Answered By - musicamante
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.