PDA

View Full Version : Problems with QTextEdit::cursorRect()



elcuco
29th March 2008, 16:27
I am playing with QTextEdit::cursorRect() and having problems. On large fonts, the rect returned to me is wrong, or I am just using this function badly. My code is basically:



// p is a QPainter
charWidth = p.fontMetrics().width( charStart );
cursor.setPosition(matchStart, QTextCursor::MoveAnchor);
r = cursorRect( cursor );
p.fillRect( r.x()+charWidth, r.y(), charWidth, r.height(), matchBracesColor );


and this is not always working (see attached image). I am also attaching a small application which reproduces this problem (the app is tested under linux only, but should work on windows). Read the header of the file for compilation instructions. The code also contains a few font definitions which work or not.

So... what am I missing here...? :)

elcuco
31st March 2008, 19:01
... no clue...?

fullmetalcoder
31st March 2008, 19:31
My guess is that there is a mixup of coordinate systems... QTextEdit uses viewport coordinates in some places and "normal" widget coordinates in other. If you are not careful enough about which coordinates you get and which you should use for each task (e.g. painting, hit detection, ...) you encounter problems as this one. How do you initialize your painter? Do you invoke any of its coordinate related functions? Do you make use of QAbstractScrollArea viewport margins?

elcuco
31st March 2008, 21:49
I posted the code since it answers a lot of things:

1) the painter is initialized to the viewport.
2) I do not apply any transformations to the painter (is this what you mean?)
3) I used the viewport margins, but I am not sure it is the cause, since (IMHO) if it was, I would see a constant shift of the position. The shift is relative to the font size on this example.

fullmetalcoder
1st April 2008, 10:34
Proposed fix (not perfect but way better than what you achieved previously) :

p.fillRect( r.x() + r.width() / 2, r.y(), charWidth, r.height(), matchBracesColor );

It falls down to replacing charWidth by r.width() / 2. This is because :

charWidth depends on the "matched" char while cursor is placed between characters bounds...
cursor is in the middle of the rect returned by cursorRect