【发布时间】:2018-03-08 11:58:59
【问题描述】:
我有包含许多 QLineEdit 的 GUI,我希望用户再次访问它以修改他的输入时将其清除,我在设计中使用 PyQt5,在脚本中使用 python 3,这里需要什么信号?
【问题讨论】:
标签: python-3.x pyqt5
我有包含许多 QLineEdit 的 GUI,我希望用户再次访问它以修改他的输入时将其清除,我在设计中使用 PyQt5,在脚本中使用 python 3,这里需要什么信号?
【问题讨论】:
标签: python-3.x pyqt5
解决方案是继承 QLineEdit 并覆盖其 focusInEvent 方法以在行编辑获得焦点时发出信号。然后将该信号连接到清除行编辑的方法。
这是一个例子:
class GUITest(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.layout = QtWidgets.QGridLayout()
self.line_edit = CustomLineEdit()
self.line_edit_two = CustomLineEdit()
self.line_edit.focus_in.connect(lambda: self.clear_line_edit(self.line_edit))
self.line_edit_two.focus_in.connect(lambda: self.clear_line_edit(self.line_edit_two))
self.layout.addWidget(self.line_edit)
self.layout.addWidget(self.line_edit_two)
self.setLayout(self.layout)
def clear_line_edit(self, line_edit):
line_edit.clear()
class CustomLineEdit(QtWidgets.QLineEdit):
focus_in = QtCore.pyqtSignal()
def __init__(self):
super().__init__()
def focusInEvent(self, QFocusEvent):
self.focus_in.emit()
【讨论】:
self.__init__ 不接受任何参数时提供了一个参数。这是另一个问题的问题。不过,在就该错误提出另一个问题之前,我建议您阅读How to ask a good question.
我找到了我的答案here,下面的代码只是将点击信号添加到任何小部件,不支持点击事件(我在此处的 QlineEdit 中使用它)
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def clickable(widget):
class Filter(QObject):
clicked = pyqtSignal()
def eventFilter(self, obj, event):
if obj == widget:
if event.type() == QEvent.MouseButtonRelease:
if obj.rect().contains(event.pos()):
self.clicked.emit()
# The developer can opt for .emit(obj) to get the object within the slot.
return True
return False
filter = Filter(widget)
widget.installEventFilter(filter)
return filter.clicked
【讨论】: