如何检查lineedit是否具有焦点?

时间:2019-09-11 16:13:28

标签: python pyqt pyqt5

我有一个行编辑,其中我需要对“ if-statement”进行“布尔”检查,如以下代码所示: 但是在“点击语法”中键入什么来验证用户是否准备输入?

if self.lineEdit."syntax for clicked for edit"(True):
  {
   "any code hear"
  }

1 个答案:

答案 0 :(得分:2)

如果要检测QLineEdit之类的小部件何时接收或失去焦点,则必须分别覆盖focusInEvent()focusOutEvent()方法。

在以下示例中,我创建了在这些事件中发出的信号:

from PyQt5 import QtCore, QtWidgets


class LineEdit(QtWidgets.QLineEdit):
    focus_in_signal = QtCore.pyqtSignal()
    focus_out_signal = QtCore.pyqtSignal()

    def focusInEvent(self, event):
        self.focus_in_signal.emit()
        super().focusInEvent(event)

    def focusOutEvent(self, event):
        super().focusOutEvent(event)
        self.focus_out_signal.emit()


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        le = LineEdit()
        le.focus_in_signal.connect(self.focus_in)
        le.focus_out_signal.connect(self.focus_out)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(QtWidgets.QLabel("Label"))
        lay.addWidget(le)
        lay.addWidget(QtWidgets.QPushButton("Button"))

    @QtCore.pyqtSlot()
    def focus_in(self):
        print("focus in")

    @QtCore.pyqtSlot()
    def focus_out(self):
        print("focus out")


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = Widget()
    w.show()

    sys.exit(app.exec_())

另一种方法是使用来自QApplication的focusChanged()信号:

from PyQt5 import QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        QtWidgets.QApplication.instance().focusChanged.connect(self.on_focusChanged)

        self.le = QtWidgets.QLineEdit()

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(QtWidgets.QLabel("Label"))
        lay.addWidget(self.le)
        lay.addWidget(QtWidgets.QPushButton("Button"))

    @QtCore.pyqtSlot("QWidget*", "QWidget*")
    def on_focusChanged(self, old, now):
        if self.le == now:
            print("self.le received focus")
        elif self.le == old:
            print("self.le lost focus")


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = Widget()
    w.show()

    sys.exit(app.exec_())

如果您想同步验证小部件是否具有焦点,则可以使用hasFocus()方法。