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

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

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?


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.

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 not automatically set input focus when the dialog is shown.


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


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

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

before show() or exec() .

链接地址: http://www.djcxy.com/p/1024.html

上一篇: 大O,你如何计算/估计它?

下一篇: 如何将输入焦点设置为Qt中显示的对话框?