windows 如何将输入焦点设置为 Qt 中显示的对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2903144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:31:08  来源:igfitidea点击:

How to set input focus to a shown dialog in Qt?

c++windowsqt

提问by Jake Petroules

In a button click slot, I create and exec()a dialog with a NULL parent. Inside the dialog's constructor, I have:

在按钮单击槽中,我创建exec()了一个带有 NULL 父级的对话框。在对话框的构造函数中,我有:

this->activateWindow();
this->raise();
this->setFocus();

The dialog is application modal and has strong focus. However, it does NOT respond to keyboard events until I click on it. How do I make the dialog get focus without having to click it?

该对话框是应用程序模式的并且具有很强的焦点。但是,在我单击它之前,它不会响应键盘事件。如何使对话框获得焦点而无需单击它?

采纳答案by Jake Petroules

The problem was that I was setting the Qt:Tool window flag. Using Qt::Popup or Qt::Window instead will cause input focus is automatically set when the dialog is shown.

问题是我正在设置 Qt:Tool 窗口标志。使用 Qt::Popup 或 Qt::Window 将导致在显示对话框时自动设置输入焦点。

I used Qt::Window myself. Some of the other flags will probably work as well, but the main thing is that a QDialog with the Qt::Tool flag will notautomatically set input focus when the dialog is shown.

我自己使用 Qt::Window。其他一些标志可能也能工作,但主要是带有 Qt::Tool 标志的 QDialog在对话框显示时不会自动设置输入焦点。

回答by Uga Buga

In my case even settings Qt::Window didn't do the trick. I had to

就我而言,即使设置 Qt::Window 也无法解决问题。我不得不

QMetaObject::invokeMethod(widgetToFocus, "setFocus", Qt::QueuedConnection);

before show()or exec().

之前show()exec()

回答by Naruto

Install the Event filter for the dialog.

为对话框安装事件过滤器。

classObject->installEventFilter(this);

void className::keyPressEvent(QKeyEvent *event)
{
   if (event->key() == Qt::Key_Space) 
    {
   focusNextChild();
    }
   else 
   {
  QLineEdit::keyPressEvent(event);
   }
}

for more info refer here. http://doc.trolltech.com/4.6/eventsandfilters.html

有关更多信息,请参阅此处。 http://doc.trolltech.com/4.6/eventsandfilters.html