参考:
https://blog.csdn.net/qq_27061049/article/details/101550616
方法一:
在PyQt中,可以通过重写QTextEdit的keyPressEvent()函数来捕获Enter按键。下面是示例代码:
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit
from PyQt5.QtCore import Qt
import sysclass MyTextEdit(QTextEdit):def keyPressEvent(self, event):if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:# 处理Enter按键事件print("Enter按键被触发")if __name__ == '__main__':app = QApplication(sys.argv)mainWin = QMainWindow()textEdit = MyTextEdit(mainWin)mainWin.setCentralWidget(textEdit)mainWin.show()sys.exit(app.exec())
这段代码创建了一个自定义的MyTextEdit类,该类继承自QTextEdit并重写了其keyPressEvent()函数。当用户按下Enter或者返回键时,会打印"Enter按键被触发"。
方法二:
自定义组件
主界面 testEdit.py
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.12.2
#
# WARNING! All changes made in this file will be lost!
import sysfrom PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplicationfrom myTextEdit import myTextEditclass Ui_MainWindow(QMainWindow):def __init__(self ):super().__init__()self.setObjectName("self")self.resize(800, 600)self.centralwidget = QtWidgets.QWidget(self)self.centralwidget.setObjectName("centralwidget")self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)self.verticalLayoutWidget.setGeometry(QtCore.QRect(160, 30, 160, 80))self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)self.verticalLayout.setContentsMargins(0, 0, 0, 0)self.verticalLayout.setObjectName("verticalLayout")# self.textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget) # 这里替换自己定义的 QTextViewself.textEdit = myTextEdit(self.verticalLayoutWidget)self.textEdit.setObjectName("textEdit")self.textEdit.setText("Hello")self.verticalLayout.addWidget(self.textEdit)self.setCentralWidget(self.centralwidget)self.menubar = QtWidgets.QMenuBar(self)self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 19))self.menubar.setObjectName("menubar")self.setMenuBar(self.menubar)self.statusbar = QtWidgets.QStatusBar(self)self.statusbar.setObjectName("statusbar")self.setStatusBar(self.statusbar)self.retranslateUi()QtCore.QMetaObject.connectSlotsByName(self)def retranslateUi(self):_translate = QtCore.QCoreApplication.translateself.setWindowTitle(_translate("MainWindow", "MainWindow"))if __name__ == "__main__":app = QApplication(sys.argv)win = Ui_MainWindow()win.show()sys.exit(app.exec_())
2)自定义的QTextEdit文件
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qtclass myTextEdit(QtWidgets.QTextEdit): #继承 原本组件def __init__(self,parent):QtWidgets.QTextEdit.__init__(self)self.parent = parentdef keyPressEvent(self, event):QtWidgets.QTextEdit.keyPressEvent(self,event)print('press',event)if event.key() == Qt.Key_Return: #如果是Enter 按钮print('success press enter key',self.toPlainText())