PDA

View Full Version : Injecting key events at the QApplication level



sraju
30th January 2014, 20:08
I am trying to inject the key event to QApplication using following code.

KeyHandler.h

class KeyHandler :
public QObject,
public QWSKeyboardHandle
{
public:
void initialize();

protected slots:
void injectKeyEvent();

private:
int fd;
QSocketNotifier *pKeyNotifier;
...
...
...

};

KeyHandler.cpp



#include <iostream>

#include <unistd.h>

#include <fcntl.h>

#include <linux/input.h>

......

const char* POWER_KEY_DEVICE = "/dev/event0";


void KeyHandler::initialize()
{

fd = open(POWER_KEY_DEVICE, O_RDONLY, 0);

if(0 <= fd)
{
std::cerr<<"Could not open file descriptor the key device.";
}

pKeyNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);

connect(
pKeyNotifier,
SIGNAL(activated(int)),
this,
SLOT(injectKeyEvent())
);
}


KeyHandler::injectKeyEvent()
{
input_event sampleKeyEvent;

ssize_t readStatus = read(fd, &sampleKeyEvent, sizeof(struct input_event);

if ((0 < readStatus) && (KEY_POWER == sampleKeyEvent.code))
{
// Prepare QKeyEvent with Q Key code
QKeyEvent *pKeyEvent = new QKeyEvent(
((0 == sampleKeyEvent.value) ? QEvent::KeyRelease : QEvent::KeyPress),
Qt::Key_Q,
Qt::NoModifier
);

std::cout << "Post QKeyEvent " << std::endl;
QCoreApplication:ostEvent(qApp, pKeyEvent);

/* Used sendEvent for test:
QCoreApplication::sendEvent(qApp, &keyEvent);
*/
}
}


Question:

- Is this way to inject Key input to QApplication? OR
- Am I missing anything here?
- Will the event posted to QApplication always be captured by MainWidget?

anda_skoa
31st January 2014, 10:38
I think you need to send the event to the widget that should recieve it.

If you want the main widget to receive it, post to it. You could alos post to the focus widget.

Cheers,
_