Reputation: 4720
I am implementing a custom context menu that is basically a widget called gripmenu
containing several other widgets. If the user left clicks, this menu should appear. To hide or delete it if the user clicks outside of it, I need to somehow check if the user click somewhere else. My plan is to ask all its child widgets for ->hasFocus()
and if none hasFocus, I will close the menu. But unfortunately I can't set the focus. Why? My code is:
gripmenu = new GripMenu(this);
gripmenu->setFocus();
And in the gripmenu
's constructor:
GripMenu::GripMenu(){
[... set things up]
ui->lineEdit->setFocus(); // or any other widget to focus,
// even this->setFocus() does not work: see below:
qDebug() << ui->lineEdit->hasFocus(); // returns false!
}
How is it possible that there is no focus immediately after I just set it?
At the end my goal is to mimic a typical context-menu behaviour (meaning that the menu is closed when clicked somewhere else). So if you have better suggestions on how to tackle it, please hint me that way!
EDIT:
I got it working. The hint of Frank Osterfeld was really useful. Still I had to add a "gripmenu->activate()" in the widget "A" that created(needed) the gripmenu, because without it, the active widget would still be "A" after the mouse got released.
Upvotes: 4
Views: 6997
Reputation: 14708
Widget normally won't be shown, redrawn or get focus immediately, so synchronous call is useless.
Why don't you use QWidgetAction
to embed widgets into a normal menu instead of hacking through signal handling?
Upvotes: 0
Reputation: 131
Try the code below, it should work:
QTimer::singleShot(0, lineEdit, SLOT(setFocus()));
Upvotes: 5