3
votes

I'm trying to add a container for showing the line numbers of a QTextEdit. From what I have seen so far I need to add a QAbstractScrollArea at the first step.

The problem is that when I add the QAbstractScrollArea, the QTextEdit render read-only. Almost read-only, I can drag&drop text but I don't have any cursor to input text.

Any ideeas? Thanks!

mainWindow = QMainWindow()
textEdit = QTextEdit(mainWindow)
textDocument = QTextDocument(textEdit)
...
# adding some text do textEdit
...

scrollArea = QAbstractScrollArea()
scrollArea.setViewport(textEdit)
scrollArea.setViewportMargins(20, 0, 0, 0)
mainWindow.setCentralWidget(scrollArea)
mainWindow.show()
2

2 Answers

1
votes

I'm not sure you should call setViewport at all.

QTextEdit already inherits from QAbstractScrollArea, so all you have to to is reserve the margin on its left, and either paint the line number or place a static widget that will display the line numbers in that margin.

There is already an example in the documentation (in C++) that does just that: Qt Code Editor example.

-1
votes

Note, that your TextEdit located on QMainWindow widget, but QScrollArea on QMainWidow::centralWidget(). It is different widgets, and centralWidget just above QMainWindow. It means that when you clicking on QTextEdit area in fact you clicking to the scrollArea widget, and not to QTextEdit.

Try this code:

    mainWindow = QMainWindow()    
    scrollArea = QAbstractScrollArea()
    scrollArea.setViewport(textEdit)
    scrollArea.setViewportMargins(20, 0, 0, 0)
    mainWindow.setCentralWidget(scrollArea)

    textEdit = QTextEdit(mainWindow.centralWidget())
    textDocument = QTextDocument(textEdit)
    ...
    # adding some text do textEdit
    ...

    mainWindow.show()