开发者

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

In a button clic开发者_如何学编程k 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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜