PDA

View Full Version : 'Modifier' key notification (eg. Shift, Ctrl, Alt)



squidge
13th November 2009, 14:34
Is there a way of getting an event or slot called when a modifier key such as Shift, Ctrl, or Alt has been pressed regardless of what widget currently has the focus?

So the user presses the left Shift button and an event handler gets called to tell the app that the shift button has been pressed. It doesn't matter if it can't differentiate between left shift and right shift.

It is important that the widget doesn't need focus in order to get the event.

JohannesMunk
16th November 2009, 15:43
Hi there!

I guess you have thought of eventFilters?



class Widget : public QWidget
{ Q_OBJECT
public:
Widget(QWidget* parent = 0) : QWidget(parent)
{
QVBoxLayout* l = new QVBoxLayout();
QLineEdit* a = new QLineEdit();
a->installEventFilter(this);
l->addWidget(a);
QLineEdit* b = new QLineEdit();
b->installEventFilter(this);
l->addWidget(b);
QLineEdit* c = new QLineEdit();
c->installEventFilter(this);
l->addWidget(c);
statusL = new QLabel();
l->addWidget(statusL);
setLayout(l);
}
protected slots:
void resetStatus()
{
statusL->setText("");
}
protected:
bool eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Shift)
{
statusL->setText("Shift pressed");
}
if (keyEvent->key() == Qt::Key_Control)
{
statusL->setText("Ctrl pressed");
}
QTimer::singleShot(500, this, SLOT(resetStatus()));
}
// standard event processing
return QObject::eventFilter(obj, event);
}
private:
QLabel* statusL;
};
HIH

Johannes

JohannesMunk
16th November 2009, 15:50
If you want it application wide, why not install an event filter for your app:



QApplication a(argc, argv);
Widget* w = new Widget();
a.installEventFilter(w);
w->show();
return a.exec();
Thats saves you the installation of the event filter for each widget.

Johannes

squidge
16th November 2009, 17:12
I didn't want to install an application-level event filter as I didn't want to slow down the main message loop, but it seemed that was the only way, so I redesigned the way everything worked and used another method (only pickup the modifier key notification from just certain main widgets).