Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QWidget setFocus does nothing

Tags:

c++

focus

qt

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.

like image 875
user2366975 Avatar asked Sep 18 '25 10:09

user2366975


1 Answers

Try the code below, it should work:

QTimer::singleShot(0, lineEdit, SLOT(setFocus()));
like image 164
Rashid Mansouri Avatar answered Sep 21 '25 01:09

Rashid Mansouri