PDA

View Full Version : Crazy QPlainTextEdit::document() behavior



Lykurg
10th March 2010, 13:50
Hi,

I have following class (simplified...):
class MyLabel : public QLabel
{
Q_OBJECT
public:
explicit MyLabel(QWidget *parent = 0, Qt::WindowFlags f = 0);

protected:
void paintEvent(QPaintEvent *event);

private:
QPlainTextEdit *m_doc; //it is hidden, only for storing reason.
};

So assume there is some content in the text edit and I do this:
void MyLabel::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter p(this);
m_doc->document()->setPageSize(rect().size());
m_doc->document()->drawContents(&p, rect());
}
nothing is shown, but when I have this:

void MyLabel::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter p(this);
QTextDocument *d = m_doc->document()->clone();
d->setPageSize(rect().size());
d->drawContents(&p, rect());
d->deleteLater();
}
everything is painted well. But why I have to clone the document??? That's not very performant... What might be the reason why I am not able to use QPlainTextEdit::document() directly?

Thanks

toutarrive
10th March 2010, 15:58
Maybe this link could be useful to you.
http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg19787.html

excerpt :

And yet in the latter case, drawContents() renders nothing at all. Cursory
investigation points to a different QAbstractTextDocumentLayout implementation
under the hood depending on the TextEdit flavor in use.

Lykurg
11th March 2010, 17:18
Ok thanks, that is really strange. But I feel better now, that I am not the only one having that trouble...

wysota
11th March 2010, 17:23
Why don't you use QTextDocument directly? What do you need QPlainTextEdit for?

Lykurg
11th March 2010, 17:55
Why don't you use QTextDocument directly? What do you need QPlainTextEdit for?

Today I figured out that my way wont work - beside that issue :( So I don't need it any more but I have had to use QPlainTextEdit since I need the functionality of getting the underlaying word at a specific point (mousepress) and therefore QPlainTextEdit::cursorForPosition() was perfect.

So for future: Do you know such a feature (QPoint -> QTextCursor) with QTextDocument?

wysota
11th March 2010, 19:41
QTextDocument has a layout which has a QAbstractTextDocumentLayout::hitTest() method that returns a position in the document based on coordinates. Knowing the position you can create a QTextCursor and use QTextCursor::setPosition() to position the cursor in appropriate place so that you can fetch the word underneath.

Lykurg
11th March 2010, 22:25
Great! Thanks a lot. Haven't know about the hitTest() function.

wysota
11th March 2010, 22:26
Until I had a look at the docs today, I have been unaware of it as well ;) "Use the docs, Luke... use the docs..."

Lykurg
11th March 2010, 22:36
"Use the docs, Luke... use the docs..."
Unfortunately my name is not Luke.:rolleyes:
Yeah, ok, temporary - hope so - incompetence...