gpt4 book ai didi

python - QLineEdit 上的事件离开

转载 作者:行者123 更新时间:2023-12-04 09:43:16 28 4
gpt4 key购买 nike

如果用户在 QLineEdit 中键入文本并离开 QLineEdit 输入字段,我想执行一些操作。

关于focusInEvent 的解释不多。我正在使用 Python 和 PySide2。但所有信息都有帮助。

def check_focus(self, event):
print('Focus in event')
# Way one I tried
if QtGui.QFocusEvent.lostFocus(self.LE_sample_input_01):
if self.LE_sample_input_01.text():
print("Lost focus")

# Way two I tried
if event.type() == QtCore.QEvent.FocusIn:
if self.LE_sample_input_01.text():
print(f"Lost focus")

# Way three I tried
if self.LE_sample_input_01.focusInEvent(event)

带有两个 QLineEdits 的简单示例

所以留下一个条目是可能的

from PySide2 import QtWidgets, QtCore, QtGui
from PySide2.QtGui import QIcon


class QTApp(QtWidgets.QWidget):
def __init__(self):
super(QTApp, self).__init__()

self.LE_sample_input_01 = QtWidgets.QLineEdit()
self.LE_sample_input_02 = QtWidgets.QLineEdit()

layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.LE_sample_input_01)
layout.addWidget(self.LE_sample_input_02)
self.setLayout(layout)

def check_focus(self, event):
print('focus out event')
# if QtGui.QFocusEvent.lostFocus(self.LE_client_name):
# print("lost focus") self.LE_client_name.focusInEvent(event)
if event.type() == QtCore.QEvent.FocusIn:
if self.LE_sample_input_01.text():
print(f"Lost focus")

if __name__ == '__main__':
app = QtWidgets.QApplication()
qt_app = QTApp()
qt_app.show()
app.exec_()

最佳答案

check_focus 方法不存在,所以它显然不会工作。如果你想监听来自另一个 QObject 的事件,比如 QWidet 那么你应该使用 eventFilter :

from PySide2 import QtWidgets, QtCore, QtGui


class QTApp(QtWidgets.QWidget):
def __init__(self):
super(QTApp, self).__init__()

self.LE_sample_input_01 = QtWidgets.QLineEdit()
self.LE_sample_input_02 = QtWidgets.QLineEdit()

layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.LE_sample_input_01)
layout.addWidget(self.LE_sample_input_02)

self.LE_sample_input_01.installEventFilter(self)
self.LE_sample_input_02.installEventFilter(self)

def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.FocusIn:
print("FocusIn")
if obj is self.LE_sample_input_01:
print("LE_sample_input_01")
elif obj is self.LE_sample_input_02:
print("LE_sample_input_02")
elif event.type() == QtCore.QEvent.FocusOut:
print("FocusOut")
if obj is self.LE_sample_input_01:
print("LE_sample_input_01")
elif obj is self.LE_sample_input_02:
print("LE_sample_input_02")
return super(QTApp, self).eventFilter(obj, event)


if __name__ == "__main__":
app = QtWidgets.QApplication()
qt_app = QTApp()
qt_app.show()
app.exec_()

关于python - QLineEdit 上的事件离开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62239538/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com