How to avoid QSyntaxHighlighter::highlightBlock blocking the UI thread
-
I currently use a subclass of QSyntaxHighlighter to highlight my document. In the highlight example, everything was okay, because the tokenization is implemented using regular expressions, and can be done in a local range.
But I prefer to have a parser which provides more semantic information, so I use libclang as a backend. The parser of libclang literally can take a LONG time to gather all the information. During this process, the UI thread is blocked, for highlightBlock seems to be called synchronized, i.e. the UI thread waits for the function to finish.
So I wonder whether there is a way to make this process asynchronous so that the UI is no longer blocked during the highlight process.
-
You need to avoid doing the heavy task in UI Thread. Move your lib clang functionality concurrent task. You use QtConcurrent or use QThread to make the task concurrent.
-
I think I understand that I should move the parsing task out of the function, but the problem really is how.
The main difficulty is: the clang API needs a source position to locate the token information, so I could only update the parse tree AFTER the text changes. But as I experimented, the signal
textChanged
orcontentsChanged
are both emitted after the slothighlightBlock
is called (highlightBlock
is called immediately after the text changes), so I had no opportunity to parse the file in advance.After
highlightBlock
returns, I found no approach to highlight the text, even if I have already known how it should be highlighted.So is there any way that I can somehow delay the highlight process, and do it when the application is fully prepared?