[英]QWidget setFocus does nothing
I am implementing a custom context menu that is basically a widget called gripmenu
containing several other widgets.我正在实现一个自定义上下文菜单,它基本上是一个名为gripmenu
的小部件, gripmenu
包含其他几个小部件。 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.我的计划是询问它的所有子小部件->hasFocus()
,如果没有 hasFocus,我将关闭菜单。 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::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. Frank Osterfeld 的暗示非常有用。 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.我仍然必须在创建(需要)gripmenu 的小部件“A”中添加一个“gripmenu->activate()”,因为没有它,活动小部件在鼠标被释放后仍将是“A”。
试试下面的代码,它应该可以工作:
QTimer::singleShot(0, lineEdit, SLOT(setFocus()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.