PyQT5中如何通过代码让QTextEdit自动获取光标焦点?
PyQt5中让QTextEdit自动获取焦点的方法
直接调用QTextEdit控件的setFocus()方法即可实现自动获取焦点,这是控件级别的焦点设置,和用于文本光标的QTextCursor不是一回事。
示例代码
import sys from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit, QPushButton, QVBoxLayout class InputWindow(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.text_edit = QTextEdit() self.post_btn = QPushButton("发布") self.post_btn.clicked.connect(self.handle_post) layout = QVBoxLayout() layout.addWidget(self.text_edit) layout.addWidget(self.post_btn) self.setLayout(layout) self.setWindowTitle("自动获取焦点示例") def handle_post(self): # 提取文本内容并处理 content = self.text_edit.toPlainText() print(f"已发布内容: {content}") # 可选:清空文本框 self.text_edit.clear() # 让QTextEdit自动获取焦点 self.text_edit.setFocus() if __name__ == "__main__": app = QApplication(sys.argv) window = InputWindow() window.show() sys.exit(app.exec_())
进阶:设置光标位置
如果需要在获取焦点后让光标定位到文本末尾(比如清空文本框后),可以结合QTextCursor实现:
def handle_post(self): content = self.text_edit.toPlainText() print(f"已发布内容: {content}") self.text_edit.clear() # 移动光标到文本末尾 cursor = self.text_edit.textCursor() cursor.movePosition(cursor.End) self.text_edit.setTextCursor(cursor) # 获取焦点 self.text_edit.setFocus()
内容的提问来源于stack exchange,提问作者yacobkennedy
相关产品推荐
相关产品推荐

