Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...