tags:

views:

158

answers:

2

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?

A: 

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

Shadow
The class is just a QDialog-derived class, with the following window flags set: `(Qt::CustomizeWindowHint | Qt::FramelessWindowHint | Qt::Tool | Qt::WindowStaysOnTopHint` It has no children and no parent.
Jake Petroules
ya, what ever, for dialog you want to get the keyboard events, install the event filter for dialog, in dialog constructor you write this->installEventFilter(this); igonre the function "focusNextChild()" in my sample above. in the dialog herder file declare keyPressEvent function and cpp file provide the implementation as above
Shadow
So do you mean this? this->installEventFilter(this); void QDialogDerived::keyPressEvent(QKeyEvent *event) { QLineEdit::keyPressEvent(event); // do my processing here? }
Jake Petroules
ya there you check the key type based on the event, like Space or enter key.. etc...
Shadow
I tried that and it did not work. See, the problem is, when the dialog is shown, it does not have input focus. *I can click on the dialog with the mouse and it gets input focus just fine.* I need to make the dialog *take input focus automatically* without having to click on it first.
Jake Petroules
A: 

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.

Jake Petroules