PDA

View Full Version : Trigger QAction by 'Key_Escape'



Raccoon29
28th March 2008, 09:26
Hi all,
I'm trying to install a global action for a QWidget that has to be triggered when 'Esc' is pressed.

I try this code:


vClose=new QAction(this);
vClose->setShortcut(Qt::Key_Escape);
connect(vClose,SIGNAL(triggered()),this,SLOT(quick Close()));
addAction(vClose); // I'm in a QWidget subclass

but it doesn't work. The function quickClose() is not called.
Instead if I put another key (such as Qt::Key_F4 or Qt::Key_F7, etc...) it gets called normally.
I could understand that Qt::Key_Escape and Qt::Key_Enter behave in a their own way...
So, what is my noobie mistake? :)

yogeshm02
28th March 2008, 16:30
It should work. Are you inside custom widget inherited directly from QWidget or some other class like QDialog? Esc key might already be being used by that.

Raccoon29
28th March 2008, 17:44
It should work. Are you inside custom widget inherited directly from QWidget or some other class like QDialog? Esc key might already be being used by that.
No, before was inherited from QDialog, but since there Esc forces the dialog to close (as expected by QDialog), I changed its ancestor and now the class is inherited directly from QWidget:

class frmcontact:public QWidget
The fact that other keys work but not Esc and Enter is strange...
thank you for the suggestion, any other idea or I have to try reimplementing onKeyPress (such a bad thing here...)?

jpn
28th March 2008, 18:43
You should be using QShortcut:


#include <QtGui>

int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QWidget w;
new QShortcut(Qt::Key_Escape, &w, SLOT(close()));
w.show();
return app.exec();
}

Raccoon29
28th March 2008, 19:16
You should be using QShortcut:


#include <QtGui>

int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QWidget w;
new QShortcut(Qt::Key_Escape, &w, SLOT(close()));
w.show();
return app.exec();
}

Thank you, even if I discovered that my solution worked too (so falled for some internal troubles that I'm going to investigate about), using QShortcut seems much more clear for this job.

Raccoon29
3rd April 2008, 10:24
Ok, I solved it.
All has been caused by a shortcut that I set in QtDesigner... and I forgot...

So if QActions are not triggered, it is most because it encountered conflicts when triggering.
So take a look to all QAction implementations ;)

Hope to be usefull for someone else.