0

I've been building a GUI with a QTextEdit object and I want to add a QPushButton that moves the cursor down to a new line.

Edit: Someone suggested this question might answer mine: Moving the cursor in a PyQt5 text edit doesn't work

But it doesn't because after crashing my program the debugger says "QTextCursor object has no attribute 'Left'." In the comments under that answer it says to try "setTextCursor" but again... same issue.

Edit: Updated example

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.layout = QVBoxLayout()
        self.w = QTextEdit()
        self.cursor = self.w.textCursor()
        self.button = QPushButton('Button')
        self.button.clicked.connect(self.nextBlock)
        # Add to layout
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.w)
        self.setLayout(self.layout)

    def nextBlock(self):
        self.w.moveCursor(QTextCursor.NextBlock)
        QTimer.singleShot(0, self.w.setFocus)

def main():
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()
  • No. It gives no indication how to move to next block. self.cursor.movePosition(self.cursor.NextBLock)? Doesn't work. –  Feb 16 '21 at 23:18
  • use `from PyQt5.QtGui import QTextCursor` `self.cursor.moveCursor(QTextCursor.NextBlock)`. If it doesn't work then you probably have another error so you need to provide an MRE – eyllanesc Feb 16 '21 at 23:30
  • @eyllanesc thanks for the suggestion. I tried this and still didn't work. Updated my question with code example. –  Feb 17 '21 at 00:04
  • TYPO: change `self.button.clicked.connect(self.moveCursor())` tp `self.button.clicked.connect(self.moveCursor)` – eyllanesc Feb 17 '21 at 00:05
  • Thanks. Still same problem though. Crash and debugger says 'QTextCursor' object has no attribute 'moveCursor'. –  Feb 17 '21 at 00:07
  • QTextCursor does not have the moveCursor method but rather the QTextEdit: https://doc.qt.io/qt-5/qtextedit.html#moveCursor , also the cursor is only visible when the QTextEdit has focus so it uses the following: `def moveCursor(self):` `self.w.moveCursor(QTextCursor.NextBlock)` `self.w.setFocus()` – eyllanesc Feb 17 '21 at 00:14
  • I updated the code example with what I think you mean, and changed method name to avoid confusion, but still same problem. –  Feb 17 '21 at 00:23
  • 1
    I have tested and it works correctly, on the other hand it shows the imports in addition to pointing out the new error message, and do not forget to save the changes :-) – eyllanesc Feb 17 '21 at 00:25
  • After restarting PyCharm I got it. Thanks! –  Feb 17 '21 at 00:33

0 Answers0