can't get format under cursor of a QTextEdit
Hi.
I have a QTextEdit subclass coupled with a QSyntaxHighlighter. After the syntax is highlighted I try to get the char format and the text under a certain position. The text returns correctly, but the format I get seems to be the the default format and not the format I set on the highlighter at this position.
This is the code:
Code:
{
if (format != NULL)
{
*format = cursor.charFormat();
}
QString rc
= cursor.
selectedText();
cursor.clearSelection();
return rc;
}
Re: can't get format under cursor of a QTextEdit
What about using QTextCursor::selection () ..
Re: can't get format under cursor of a QTextEdit
The reason I need the character format is because I saved a value in the user property of that format.
I don't see how I can access that with the selection() method.
Re: can't get format under cursor of a QTextEdit
QSyntaxHighlighter does not change the character format directly in the QTextEdit. You cannot retrieve the format via QTextCursror::charFormat. QSyntaxHighlighter sets the format in additionalFormats as part of the block layout. You can get a list of all formats used in the block the cursor is in by using textCursor().block().layout()->additionalFormats(). This will be a list of FormatRange objects. Get the cursor position in the block using textCursor().positionInBlock() and loop over the items in additionalFormats checking if the cursor is within the item's range (the start of is relative within the block) and if the format matches what you're looking for.
Here is an excerpt from a project I'm working on where I'm checking the formatting set by QSyntaxHighlighter for offering spell checking suggestions.
Code:
int pos = c.positionInBlock();
foreach
(QTextLayout::FormatRange r, textCursor
().
block().
layout()->additionalFormats
()) { if (pos >
= r.
start && pos <
= r.
start + r.
length && r.
format.
underlineStyle() == QTextCharFormat::SpellCheckUnderline) { c.setPosition(c.block().position() + r.start);
setTextCursor(c);
offerSpelling = true;
break;
}
}
Re: can't get format under cursor of a QTextEdit
Thanks. I've found an alternative way of achieving what I wanted in the mean time.
I'll try your solution later.