How to remove focus with QLineEdit when anywhere in the window is clicked

I am working on a custom Qt button that allows me to edit the text on a button if you double-click on it. When a button is pressed twice, QLineEdit appears, where the text on the button allows the user to edit the text on the button. My requirement is that if the user clicks anywhere in the application window, QLineEdit should disappear and cancel the editing operation. This works in some cases. In particular, it works if I click on everything that is capable of entering text. Other parts of the window do not work as expected. I click on an empty part of the application window and QLineEdit keeps focus. How to remove focus in these cases?

+5
source share
4 answers

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

Subclass QLineEdit so that I have a new type. I do not want or do not need this behavior in all instances of QLineEdit; only these specific ones.

class MyLineEdit(QtGui.QLineEdit):
    pass

Now, in my subclass of QMainWindow, I am redefining the implementation mousePressEvent(). He is currently getting a widget. If this widget is of type MyLineEdit, clear 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 leads me to the behavior I'm looking for, so if the user clicks anywhere in the application window, the focus is cleared.


: . QTreeView . , .

+8

clicked() yourLabel- > clearFocus() ( , , ).

+4

, , :

QApplication.focusWidget().clearFocus()

.

+2

++, - :

connect(myWidgets->MyLineEdit, SIGNAL(returnPressed()), this, SLOT(onLineEditDone());

void onLineEditDone()
{
    myWidgets->MyLineEdit->clearFocus();
}

editingFinished() returnPressed(), , textChanged(QString).

0

All Articles