PyQt4:为QLineEdit组合textChanged和editingFinished

时间:2012-08-29 16:08:57

标签: qt qt4 pyqt pyqt4

有没有办法将textChangededitingFinished合并为QLineEdit?问题是,即使我只将光标移离editingFinished而没有任何更改,也会发出QLineEdit。而我只想在完成编辑后执行任何更改时才发出信号。

我可以想象只存储当前文本的某个地方,将输入的文本与它进行比较,并且仅在它不同时才执行某些操作。但我想知道是否有任何纯粹基于信号处理的解决方案。

编辑:最后,我必须存储当前文本并与新文本进行比较,而不是遵循建议的解决方案。我意识到在我的应用程序“1.2345”和“1.23”将是相同的文本但是我必须在这种情况下更新一些其他值,依此类推。我非常感谢@Avaris和@ekhumoro的详细解答和评论,并且会接受它,因为它似乎解决了最初发布的问题。

2 个答案:

答案 0 :(得分:12)

修改

用于捕获手动编辑:

class MyLineEdit(QtGui.QLineEdit):
    textModified = QtCore.pyqtSignal(str, str) # (before, after)

    def __init__(self, contents='', parent=None):
        super(MyLineEdit, self).__init__(contents, parent)
        self.returnPressed.connect(self.checkText)
        self._before = contents

    def focusInEvent(self, event):
        if event.reason() != QtCore.Qt.PopupFocusReason:
            self._before = self.text()
        super(MyLineEdit, self).focusInEvent(event)

    def focusOutEvent(self, event):
        if event.reason() != QtCore.Qt.PopupFocusReason:
            self.checkText()
        super(MyLineEdit, self).focusOutEvent(event)

    def checkText(self):
        if self._before != self.text():
            self._before = self.text()
            self.textModified.emit(self._before, self.text())

修改2

用于捕获所有编辑(程序和手动):

class MyLineEdit(QtGui.QLineEdit):
    textModified = QtCore.pyqtSignal(str, str) # (before, after)

    def __init__(self, contents='', parent=None):
        super(MyLineEdit, self).__init__(contents, parent)
        self.editingFinished.connect(self.checkText)
        self.textChanged.connect(lambda: self.checkText())
        self.returnPressed.connect(lambda: self.checkText(True))
        self._before = contents

    def checkText(self, _return=False):
        if (not self.hasFocus() or _return) and self._before != self.text():
            self._before = self.text()
            self.textModified.emit(self._before, self.text())

编辑3

用于仅捕获用户的文本更改:

class MyLineEdit(QtGui.QLineEdit):
    textModified = QtCore.pyqtSignal(str, str) # (before, after)

    def __init__(self, contents='', parent=None):
        super(MyLineEdit, self).__init__(contents, parent)
        self.editingFinished.connect(self.__handleEditingFinished)
        self.textChanged.connect(self.__handleTextChanged)
        self._before = contents

    def __handleTextChanged(self, text):
        if not self.hasFocus():
            self._before = text

    def __handleEditingFinished(self):
        before, after = self._before, self.text()
        if before != after:
            self._before = after
            self.textModified.emit(before, after)

答案 1 :(得分:6)

如果您只想检测是否已进行任何更改(而不是文本是否与其启动方式不同),您可以使用modified属性{ {1}} editingFinished信号:

QLineEdit