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

I'm working on a custom Qt button that allows you to edit the text on the button if you double click it. When the button is double clicked, a QLineEdit appears where the text on the button is allowing the user to edit the text on the button. My requirement is that if the user clicks anywhere in the application window, the QLineEdit should disappear and cancel the edit operation. This works in some cases. Specifically, it works if I click on anything that is capable of text entry. Other portions of the window don't work as expected. I'll click on a blank portion of the application window, and the QLineEdit retains its focus. How can I remove its focus in these cases?

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 followed Grant Limberg instruction here but figured out that, in my case, a simple:
QApplication.focusWidget().clearFocus()
would fix the problem.

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.

If done in C++ I would do something along the lines of:
connect(myWidgets->MyLineEdit, SIGNAL(returnPressed()), this, SLOT(onLineEditDone());
void onLineEditDone()
{
myWidgets->MyLineEdit->clearFocus();
}
For this particular case I would use editingFinished() instead of returnPressed(), probably, but I would NOT use textChanged(QString).

Related

Recognize set/lose Focus-Event in QWindow

I´ve created a Qt-Quick Combo-Box that, when it will be pressed, opens a QWindow, in which I show the content within a TableView. The problem is, the focus on the TableView can´t be set.
So first question is: How can I set the Focus on my TableView (which is hosted inside my QWindow)?
Furthermore, I have to get the event, if the user clicks beside the QWindow or outside the Application. That means the focus was changed and I can close my QWindow.
So second question is: How can I get the information, that the TableView lost the focus?
Thanks in advance.
For from QWidget derived classes:
To set a focus use setFocus.
To recognize that the focus has been los, you can derive the class and override focusOutEvent or write an eventfilter.

Qt: display qgraphicsitem in a widget

I got a QGraphicsScene that contains QGraphicsItems. On clicking such an item I open a dialog. I now want the item to be displayed in an area of the dialog.
I tried a QGraphicsView (in the dialog) and "pointed" it to the item which works allmost perfectly. The problem is, that it is possible to click the item in the dialog which would open a new dialog.
So my question: is there a easy way to tell QGraphicsView to ignore any input events? If not, is there a easy way to display a QGraphicsItem within a widget?
I am feeling so stupid...
QGraphicsView::setInteractive(false) did the trick.
I am still able to move the icon with the mouse wheel but this can probably be avoided by restricting the scene rect with setSceneRect()
You can install an event filter, on the QGraphicsView, which ignores input events. The Qt documentation states:
In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.

How to focus on a next/previous widget

I am overriding the QPlainTextEdit to become a single line edit widget. In other words I want it to look like a QLineEdit but to have the extended functionality of QPlainTextEdit, such as text formatting etc.
My only trouble so far is that I do not know how to pass focus to the next/previous widget when I press Tab/Shift+Tab when the widget derived from QPlainTextEdit is in focus. I have started with overriding keyPressEvent to capture Tab key being pressed, but then what? How to change the focus from the widget?
I can only think of too complicated solutions (such as signalling to the parent that the focus should change, but this seems as stupid overkill). I bet there must be a very simple solution to this problem.
Set the tabChangesFocus property of your QPlainTextEdit object to true by using the QPlainTextEdit::setTabChangesFocus function.
I accepted the answer by thuga which is the simplest way. However I found also another one which might be more generic for widgets that do not have tabChangesFocus property. Override keyPressEvent like this:
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Tab:
self.parent().focusNextChild()
elif event.key() == QtCore.Qt.Key_Backtab:
self.parent().focusPrevChild()
There are two things you can try:
Create QAction and add it to the widget. Set QShortcut to the action with QKeySequence(Qt::Key_Tab). Connect the action whith slot which changes the focus.
or
Use directly new QShortcut(QKeySequence(Qt::Key_Tab), widgetPtr, SLOT(changeFocus()));
So there is no need now to inherit your control only to capture keyPressEvent. Note that you may need to change the shortcut context for best match to your requirements.

How to detect if focus shift from a widget inside a QWidget to one outside?

I'm programming in Python using Qt with PySide and I have custom QWidget defined in a file called editor.py which is inserted in my ui in windowUi.py using the promotion method in the Qt Designer.
The custom QWidget class defined in editor.py doesn't do much besides using Elixir to edit items in a sqlite3 database and importing a ui file (editor.ui). Inside editor.ui there are a couple of QLineEdits and QDateTime widgets.
This widget is originally hidden in the main window and showed when needed. So far so good, but the problem is that I cannot make it hide when not needed. I decided that the widget is not needed when the user clicks anywhere else in the main window that is not the editor widget imported, that is, focus shift from the QWidget.
I looked upon this question: QWidget focusOutEvent not received and realized that the QWidget is really not getting focus.
If I call setFocusPolicy(StrongFocus) on it then I can make it hide if, and only if, the user clicks on the QWidget background (not on any widget inside it) and then clicks outside.
The question is then, how can I make it such that when the user clicks outside of this widget, shifting focus from any QLineEdit or QDateTime that's inside it to something else, the QWidget then hides itself?
Doesn't QApplication:::focusChanged ( QWidget * old, QWidget * now ) do what you need? You can check if QWidget *now is one of your QLineEdits/QDateTime or not (f.e. by going up by the QObject::parent)
Simply connect to this signal before showing and disconnect after hiding.

QAction vs QToolButton and when to override the Basic class?

I've recently been studying Qt, and have the following questions:
What is the difference between QAction and QToolButton?
How do I know when to override QPushButton? For example, should I override in order to be informed when the mouse enters a QPushButton's bounds? I don't need to in order to get the signal click().
Question 1:
QActions are used to define tasks performed by an application in a way which can be understood by a number of different user interface objects. Using an example from the Qt docs for context:
A QAction is defined; it is given an icon image, a text description, a keyboard shortcut and a longer tooltip description, as well as being linked to a user defined function.
newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(tr("Create a new file"));
connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
Later in the implementation, the QAction is added both to a textual menu bar...
fileMenu->addAction(newAct);
... and an icon-based tool bar:
fileToolBar->addAction(newAct);
The menu bar uses the text description to create an entry in the menu corresponding to the action. Similarly the toolbar uses the icon set on the QAction to create an icon in the toolbar which corresponds to the action. Selecting the menu item, clicking the toolbar icon or pressing the keyboard shortcut will all result in the same effect: that defined by the linking of QAction::triggered() to newFile().
So to directly answer your question: a QAction is an abstract way of defining the various parameters and behaviour of a particular task performed by the application. A QToolbarButton is a UI object (derived from QWidget) created by a QToolbar in response to QToolbar::addAction()
Question 2:
Yes, QPushButton has a clicked() signal inherited from QAbstractButton, but it does indeed lack a way to inform when the mouse has entered its bounds. You have a couple of options in order achieve this, but first you need to first set the mouseTracking property to be enabled. This will allow you to receive mouse move events on the QPushButton even if no mouse buttons are pressed. With that done you need to explore one of the following options:
As you suggest, you could subclass QPushButton and reimplement mousePressEvent in order to respond to the mouse position.
You could install another widget as an eventFilter on the QPushButton, and watch for events of type (QEvent::MouseMove).

Resources