QScrollArea makes QTextEdit read-only

I am trying to add a container to display QTextEdit line numbers. From what I've seen so far, I need to add a QAbstractScrollArea in the first step.

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

Any ideas? Thank!

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()

      

+3


source to share


2 answers


I'm not sure what you should be calling setViewport

at all.

QTextEdit

already inherits from QAbstractScrollArea

, so all you need to do is reserve the left margin and draw the line number, or put a static widget that will display the line numbers in that box.



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

+1


source


Note that your TextEdit is on the QMainWindow widgets, but the QScrollArea on QMainWidow :: centralWidget (). These are different widgets and the centralWidget just above the QMainWindow. This means that when you click on the QTextEdit, you are actually clicking on the scrollArea widget, not the 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()

      

-1


source







All Articles