是否可以将textChangededitingFinished组合为QLineEdit?问题是即使我仅将光标从editingFinished移开而没有任何更改,也会发出QLineEdit。而我只想在完成编辑后进行任何更改时发出信号。

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

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

最佳答案

编辑

要捕获手动编辑:

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)

关于qt - PyQt4:结合textChanged和editFinished为QLineEdit,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12182133/

10-11 23:14
查看更多