QLineEdit的GUI问题

时间:2018-03-08 11:59:00

标签: python-3.x pyqt5

我有一个包含许多QLineEdit的GUI,我希望它一旦用户再次修改他的输入就被清除,我在设计中使用PyQt5并在脚本中使用python 3,这里需要什么信号?

2 个答案:

答案 0 :(得分:0)

对此的解决方案是子类化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()

答案 1 :(得分:-1)

我找到了答案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