How to remove focus from a QLineEdit when anyplace else on the window is clicked

I followed Grant Limberg instruction here but figured out that, in my case, a simple:

QApplication.focusWidget().clearFocus()

would fix the problem.


I've found a solution that seems to work, though I'm still open to other options if there are any. I'm using PyQt4, so my example is in python:

Create a subclass of QLineEdit just so I have a new type. I don't want or need this behavior on all QLineEdit instances; just these specific ones.

class MyLineEdit(QtGui.QLineEdit):
    pass

Now, in my QMainWindow subclass, I override the mousePressEvent() implementation. It gets the currently focused widget. If that widget is of type MyLineEdit, clear the focus.

class MyMainWindow(QtGui.QMainWindow):
    def ...

    def mousePressEvent(self, event):
        focused_widget = QtGui.QApplication.focusWidget()
        if isinstance(focused_widget, MyLineEdit):
            focused_widget.clearFocus()
        QtGui.QMainWindow.mousePressEvent(self, event)

    def ...

This gets me the behavior I'm looking for so that if the user clicks anywhere on the application's window, the focus is cleared.


Edit: I did find one caveat to this. I have a QTreeView in the main window. If the user clicks on the tree view, focus is not removed from the text edit field.


Catch the clicked() signal of your parent widget and call yourLabel->clearFocus() (that unfortunatelly happens to not be a slot, making things more complicated) there.


I'm not sure if this also works in Qt4 (I'm using PyQt5) but you can change the FocusPolicy of the QMainWindow or parent widget to clear the focus in the QLineEdit. As per https://doc.qt.io/qt-5/qwidget.html#focusPolicy-prop

I've changed the policy of my QMainWindow to Qt.StrongFocus and it worked like the functionality described in the question.

Tags:

Qt

Focus

Qt4