c++qtqplaintextedit

How to get the value of the distance between QPlainTextEdit's borders and its text


In QPlainTextEdit, the first typed symbol is drawn with a small offset, literally, there are a few pixels.

How do I know the value of this offset in the code? Look at the screenshot, distance between red line and selected character is what I need to know.

enter image description here

#include <QApplication>
#include <QPlainTextEdit>
#include <QPainter>


class TextEdit
    :   public QPlainTextEdit
{
protected:
    void paintEvent( QPaintEvent * e ) override
    {
        QPainter p( viewport() );
        p.setPen( Qt::red );
        p.drawRect( viewport()->rect() );

        QPlainTextEdit::paintEvent( e );
    }
};

int main( int argc, char ** argv )
{
    QApplication app( argc, argv );

    TextEdit e;
    e.resize( 100, 100 );
    e.show();

    return QApplication::exec();
}

viewportMargins().left(), contentsMargins().left() are 0.

What else?


Solution

  • The property you are looking for is not held in the viewport but in the underlying document.

    Here is the said property: QTextDocument::documentMargin().
    You can get the underlying document through QPlainTextEdit::document().

    In your example, if you display e.document()->documentMargin() you will get the value you are looking for.

    The default value is 4. You can change it with QTextDocument::setDocumentMargin().