PDA

View Full Version : can't get format under cursor of a QTextEdit



dvirtz
12th October 2011, 07:48
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:


QString LineTextEdit::getTextAndPropertyAtPosition( const QPoint & pos, QTextCharFormat *format)
{
QTextCursor cursor = cursorForPosition(pos);
cursor.select(QTextCursor::WordUnderCursor);
if (format != NULL)
{
*format = cursor.charFormat();
}
QString rc = cursor.selectedText();
cursor.clearSelection();
return rc;
}

vinodpaul
12th October 2011, 09:07
What about using QTextCursor::selection () ..

dvirtz
12th October 2011, 09:11
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.

user_none
29th October 2011, 12:55
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.



QTextCursor c = textCursor();
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);
c.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, r.length);
setTextCursor(c);
offerSpelling = true;
break;
}
}

dvirtz
1st November 2011, 12:12
Thanks. I've found an alternative way of achieving what I wanted in the mean time.
I'll try your solution later.