Moving the cursor in a PyQt5 text edit doesn't work

喜夏-厌秋 提交于 2021-01-28 07:31:41

问题


I'm contributing to Frescboaldi, a PyQt5 application and experience problems interacting with the core text edit component.

It seems whatever I try I can't get either of setPosition or movePosition to work.

The code

cursor.insertText("Hello")
cursor.setPosition(cursor.position() - 5)

properly inserts the text Hello in the document but leaves the cursor at the end of the inserted text (instead of moving it to the left by 5 characters). The first line proves that cursor, textedit and document are set up properly. trying movePosition doesn't have any effect either.

The actual goal is to insert some text, have it selected and the cursor at the end of the selection as can be seen in https://github.com/wbsoft/frescobaldi/blob/master/frescobaldi_app/cursortools.py#L179

Am I doing anything wrong here? Could this be a bug in Qt/PyQt? Or could this be an issue in PyQt5?

[Edit:] I've now confirmed with a minimal app example that the problem can't be in the larger construction of the application. In the following mini app neither setPosition nor movePosition has any effect - while insertText works well:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys

from PyQt5.QtWidgets import QApplication, QTextEdit

def main():    
    app = QApplication(sys.argv)

    w = QTextEdit()
    w.setWindowTitle('Manipulate cursor')
    cursor = w.textCursor()
    cursor.insertText("Hello World")
    # neither of the following commands have any effect
    cursor.setPosition(cursor.position() - 5)
    cursor.movePosition(cursor.movePosition(cursor.Left, cursor.KeepAnchor,  3))

    w.show()   
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

回答1:


You are working on a local copy of the text cursor returned by w.textCursor. You should call w.setTextCursor(cursor) at the end to change the visible cursor.

A second problem is that you use the output of movePosition to call movePosition again, which is not allowed:

cursor.movePosition(cursor.movePosition(cursor.Left, cursor.KeepAnchor,  3))

should be

cursor.movePosition(cursor.Left, cursor.KeepAnchor,  3)

Note that I tested it in Qt (not PyQt), but that should not make any difference, which successfully selected lo of Hello world.



来源:https://stackoverflow.com/questions/43304803/moving-the-cursor-in-a-pyqt5-text-edit-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!