Reputation: 7974
I have a widget and I want to run some function when the user presses a mouse on it. But I want to run it ONLY if the mouse press caused focus change. I tried the following:
void MyWidget::mousePressEvent(QMouseEvent *event)
{
if (hasFocus()) // WRONG: I want to check whether the widget had focus before the mouse press, but it does not work, this always returns true
{
//do something for which I need `event.pos()`
}
MyWidgetParent::mousePressEvent(event);
}
but it does not work. hasFocus()
inside mousePressEvent()
is always true, it seems that focus gets changed before mousePressEvent()
is called. On the other hand, I cannot implement this functionality in focusInEvent
because I do not know the mouse event.pos()
in it.
Any ideas how to work around this problem?
Upvotes: 2
Views: 343
Reputation: 3185
You could implement a handler for a QFocusEvent
(focusInEvent
) and check if the reason()
is a MouseFocusReason
. You can save that in a variable and in the QMouseEvent
you check and reset that variable. So if the element was focused by the mouse and you get a mouse event you know, that that mouse event caused the focus change.
Upvotes: 1