PDA

View Full Version : Keeping Shortcuts active in the MainWindow when on a modeless QDialog



Sergex
21st December 2011, 12:42
Hi,

I have an action with a keyboard shortcut in my main window that starts an operation called "process". But now I made a QDialog that pops up when a button is pressed, and in that dialog I set the value that the process operation in the main window needs. So for this I made the dialog modeless but while I'm on the dialog the keyboard shortcuts of the mainwindow don't work until I actually click on the mainwindow again. Since I vary the parameter in the QDialog I would like to not need to always click on the mainwindow after setting a value in the dialog to start a "process".

I tried doing:



//In main window

...
processAction = new QAction(this)
processAction->setShortcut(QKeySequence(Qt::Key_3));
...

myDialog = new QDialog(this)
myDialog->addAction(processAction);



But this didn't work.
Is there a way to do this??

Thanks.

Spitfire
21st December 2011, 15:24
Event Filter (http://doc.qt.nokia.com/4.7-snapshot/qobject.html#installEventFilter)to the rescue!
Install it on the dialog with main window as a filtering object and you're good to go.

Sergex
21st December 2011, 16:29
Thanks for the reply!

Yes this almost works, almost because I'm having a strange problem happening. I installed the eventFilter on the dialog like this:



//In my MainWindow

myDialog->installEventFilter(this);
...

...
bool eventFilter(QObject *obj, QEvent *e)
{
if(obj == myDialog)
{
if(e->type() == QEvent::KeyPress)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
if(keyEvent->key() == Qt::Key_3)
{
process();
return true;
}
else
return false;
}
}

return QMainWindow::eventFilter(obj, e);
}


This will only work if I set the 'if' line :
if(keyEvent->key() == Qt::Key_Shift)
..

In other words it will only go into the if(e->type() == QEvent::KeyPress), only if with the SHIFT, Control or Alt keys are presssed but not with any other keys. And since I don't want any of the modifier keys as shortcut to my function I am still stuck.

I am on Mac OS 10.6.8 if that makes any difference..

Any ideas??

Spitfire
22nd December 2011, 13:55
I don't have mac at hand to check, but I would guess this shouldn't make any difference.


bool MainWindow::eventFilter( QObject* o, QEvent* e )
{
if( e->type() == QEvent::KeyPress )
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>( e );
qDebug() << keyEvent->key();
}
return QMainWindow::eventFilter( o, e );
}
should work for any key as long as the window has the focus (it works in my case, but I'm running w7 box at the moment).