pyqt5 - python PyQt5 - 选择插入的光标文本?

我有一个QPlainTextEdit小部件,我正在尝试让光标自动选择插入的文本,


class TextBox(QPlainTextEdit):


 def __init__(self):


 QPlainTextEdit.__init__(self)



 font = QtGui.QFont()


 font.setPointSize(12)


 self.setFont(font)



 def keyPressEvent(self, keyEvent):


 super(TextBox, self).keyPressEvent(keyEvent)



 if keyEvent.key() == Qt.Key_Return :


 self.clear()



 elif keyEvent.key() == Qt.Key_Space:


 cursor = self.get_cursor()


 cursor.insertText("test") # The area of concern


 cursor.selectionStart()


 cursor.movePosition(QtGui.QTextCursor.WordLeft, QtGui.QTextCursor.KeepAnchor, 1)


 cursor.selectionEnd()


 # Moving the cursor position doesn't seem to do anything



 def get_cursor(self):


 return self.textCursor()



 def get_cursor_pos(self):


 return self.get_cursor().position()



时间:

光标必须设置为文本编辑。


class TextBox(QPlainTextEdit):


 # ...



 def keyPressEvent(self, keyEvent):


 super(TextBox, self).keyPressEvent(keyEvent)



 if keyEvent.key() == Qt.Key_Return :


 self.clear()



 elif keyEvent.key() == Qt.Key_Space:


 cursor = self.textCursor()


 cursor.insertText("test")


 cursor.movePosition(QtGui.QTextCursor.WordLeft, QtGui.QTextCursor.KeepAnchor, 1)


 self.setTextCursor(cursor)



记住,因为你调用keyPressEvent的基类实现,所以总是在"新建"文本之前有一个空格,


 def keyPressEvent(self, keyEvent):


 if keyEvent.key() == Qt.Key_Return :


 self.clear()



 elif keyEvent.key() == Qt.Key_Space:


 cursor = self.textCursor()


 pos = cursor.position()


 cursor.insertText("test")


 cursor.setPosition(pos, QtGui.QTextCursor.KeepAnchor)


 self.setTextCursor(cursor)


 # by returning, the event won't be sent to the default implementation


 return



 super(TextBox, self).keyPressEvent(keyEvent)



...