如何让 QLineEdit 检测到 Tab Key Pressing 事件
Posted
技术标签:
【中文标题】如何让 QLineEdit 检测到 Tab Key Pressing 事件【英文标题】:How to allow QLineEdit detects Tab Key Pressing event 【发布时间】:2018-12-19 17:23:50 【问题描述】:这篇文章是为了以不同的方式改写我在here 发布的问题。我想让 QlineEdit 检测到Tab Key
按调用一个名为do_something()
的方法。我从 Qt Designer 生成了以下 pyqt5
代码,其中包括名为 lineEdit
的 QlineEdit 实例。当我输入SSN
数字并按 Tab 键时,应该调用该方法。我该怎么做?
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(348, 68)
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(40, 20, 41, 16))
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(80, 20, 201, 21))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def do_something():
print('Success!')
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "SSN"))
【问题讨论】:
【参考方案1】:更简单地说,我成功地继承了 QLineEdit 并覆盖了它的事件方法,如下所示:
class EditSpec(QLineEdit):
def event(self,event):
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:
self.tabFollow()
return True
else:
return QLineEdit.event(self,event)
def tabFollow(self):
print("tab-key pressed!")
任何非制表键按下都会正常进行,而制表键按下会触发 tabFollow 方法。要添加(这很重要),重写 keyPressEvent 方法不会阻止事件通过应用程序的事件系统被触发。仅以与上述类似的方式覆盖事件方法。
【讨论】:
【参考方案2】:我之前的回答中指出的最简单的选项是使用QShorcut
,您必须作为小部件传递给QLineEdit
,并且在这种情况下必须是Qt::WidgetWithChildrenShortcut
的上下文
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(348, 68)
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(40, 20, 41, 16))
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(80, 20, 201, 21))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "SSN"))
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
shortcut = QtWidgets.QShortcut(
QtGui.QKeySequence(QtCore.Qt.Key_Tab),
self.lineEdit,
context= QtCore.Qt.WidgetWithChildrenShortcut,
activated=self.do_something)
@QtCore.pyqtSlot()
def do_something(self):
print('Success!')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())
【讨论】:
以上是关于如何让 QLineEdit 检测到 Tab Key Pressing 事件的主要内容,如果未能解决你的问题,请参考以下文章
如何通过按 Escape 键重置 QLineEdit 文本?
如何使 QPushButtons 将文本添加到 QLineEdit 框中?