nalayak
nalayak

Reputation: 27

how to check that lineedit has focus?

I have a line-edit in which i want the 'bool' check for 'if-statement' as shown in codes below: but what to type in "syntax for clicked" to verify that if the user is ready to input on that?

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

Upvotes: 1

Views: 4423

Answers (1)

eyllanesc
eyllanesc

Reputation: 244301

If you want to detect when a widget like QLineEdit receives or loses focus then you must override the focusInEvent() and focusOutEvent() methods, respectively.

In the following example I have created signals that are emitted in those events:

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_())

Another method is to use the focusChanged() signal from QApplication:

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_())

If instead you want to verify synchronously if a widget has focus you can use the hasFocus() method.

Upvotes: 4

Related Questions