For my whats failing is this code, the layout system has nothing to do, as the margins are inside the widget.

(edit: just remembered, parts of this code are based on QDevelop, so they are GPL)

Qt Code:
  1. #include <QTextEdit>
  2.  
  3.  
  4. class newedit : public QTextEdit
  5. {
  6. Q_OBJECT
  7. public:
  8. newedit(QWidget* parent);
  9.  
  10. protected:
  11. void paintEvent ( QPaintEvent * event );
  12.  
  13. };
  14.  
  15. #include "newedit.h"
  16. #include <QApplication>
  17. #include <QPainter>
  18. #include <QTextBlock>
  19. #include <QTextLayout>
  20. #include <QScrollBar>
  21.  
  22. newedit::newedit( QWidget* parent )
  23. {
  24. setViewportMargins( 50, 0, 0, 0 );
  25. }
  26.  
  27. void newedit::paintEvent( QPaintEvent * event )
  28. {
  29. QTextEdit::paintEvent( event );
  30.  
  31. int contentsY = verticalScrollBar()->value();
  32. qreal pageBottom = contentsY + viewport()->height();
  33. int m_lineNumber = 1;
  34. const QFontMetrics fm = fontMetrics();
  35. const int ascent = fontMetrics().ascent() +1;
  36.  
  37. QPainter p( this );
  38. for ( QTextBlock block = document()->begin(); block.isValid(); block = block.next(), m_lineNumber++ )
  39. {
  40. QTextLayout* layout = block.layout();
  41. const QRectF boundingRect = layout->boundingRect();
  42. QPointF position = layout->position();
  43. if ( position.y() +boundingRect.height() < contentsY )
  44. continue;
  45. if ( position.y() > pageBottom )
  46. break;
  47.  
  48. const QString txt = QString::number( m_lineNumber );
  49.  
  50. p.drawText( width() -fm.width( txt ) - 2, qRound( position.y() ) -contentsY +ascent, txt ); // -fm.width( "0" ) is an ampty place/indent
  51. }
  52.  
  53. }
To copy to clipboard, switch view to plain text mode