一、cursorPosition()方法
cursorPosition()方法用于获取QLineEdit中当前光标的位置,语法为:
pos = lineEdit.cursorPosition()
其中,pos为当前光标的位置,从0开始计数。
演示:
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget, QVBoxLayout
app = QApplication([])
window = QWidget()
lineEdit = QLineEdit()
lineEdit.setText("Hello World!")
lineEdit.setCursorPosition(6)
layout = QVBoxLayout()
layout.addWidget(lineEdit)
window.setLayout(layout)
window.show()
# 获取当前光标的位置
pos = lineEdit.cursorPosition()
print(pos)
app.exec_()
运行后,输出结果为6。
二、setCursorPosition()方法
setCursorPosition()方法用于设置QLineEdit中光标的位置,语法为:
lineEdit.setCursorPosition(pos)
其中,pos为需要设置的光标位置,从0开始计数。
演示:
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget, QVBoxLayout
app = QApplication([])
window = QWidget()
lineEdit = QLineEdit()
lineEdit.setText("Hello World!")
lineEdit.setCursorPosition(6)
layout = QVBoxLayout()
layout.addWidget(lineEdit)
window.setLayout(layout)
window.show()
# 将光标设置到第一个字符处
lineEdit.setCursorPosition(0)
app.exec_()
运行后,QLineEdit中的光标会被设置到第一个字符处。