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.
Try the code below, it should work:
QTimer::singleShot(0, lineEdit, SLOT(setFocus()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With