简体   繁体   English

如何将焦点设置在特定的小部件上

[英]How to set Focus on a specific widget

I'm trying to implement GUI with various widgets for OpenGL project. 我正在尝试使用OpenGL项目的各种小部件来实现GUI。 I have a main widget for drawing the scene. 我有一个用于绘制场景的主窗口小部件。 The OpenGL widget is associated with Key and Mouse events, therefore the focus should always be on it. OpenGL小部件与“键”和“鼠标”事件相关联,因此焦点应始终放在它上面。 I've noticed if I click on say a push button, then the focus is moved to this button which means the focus is no longer associated with OpenGL widget. 我注意到如果单击某个按钮,那么焦点将移至该按钮,这意味着焦点不再与OpenGL小部件相关联。 Clicking the widget by the mouse is not changing the focus. 用鼠标单击小部件不会改变焦点。 One of the solution is to turn off the focus for all widgets except the OpenGL widget in the GUI as follows 解决方案之一是关闭GUI中OpenGL小部件以外的所有小部件的焦点,如下所示

 ui->processButton->setFocusPolicy(Qt::NoFocus);
 ui->quitButton->setFocusPolicy(Qt::NoFocus);
 ui->clearButton->setFocusPolicy(Qt::NoFocus);
 ui->textEdit->setFocusPolicy(Qt::NoFocus);
 ui->groupBox->setFocusPolicy(Qt::NoFocus);

if I have many widgets, then this solution is annoying especially if I add widgets later on. 如果我有很多小部件,则此解决方案很烦人,尤其是如果以后再添加小部件时。 My question is is there a solution to set the focus on a specific widget? 我的问题是是否有一种解决方案可以将重点放在特定的小部件上?

Your solution is fine, you just shouldn't be enumerating widgets manually: 您的解决方案很好,您不应该手动枚举小部件:

// C++11
for (auto widget : findChildren<QWidget*>())
  if (! qobject_cast<QOpenGlWidget*>(widget)) widget->setFocusPolicy(Qt::NoFocus);

// C++98
foreach (QWidget * widget, findChildren<QWidget*>())
  if (! qobject_cast<QOpenGlWidget*>(widget)) widget->setFocusPolicy(Qt::NoFocus);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM