Reputation: 41
I use Qt to develop my application, and I want to listen the global mouse and keyboard events, so I can do something after detect these events. On windows platform, I use SetWindowsHookEx API. But I don't know how to do the similar thing on Linux.
My code on Windows as below:
/*********************listen mouse event*****************************/
mouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, NULL, 0);
if (mouseHook == NULL) {
qDebug() << "Mouse Hook Failed";
}
/*********************listen keyboard event*****************************/
keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, keyBoardProc, NULL, 0);
if (keyboardHook == NULL) {
qDebug() << "Keyboard Hook Failed";
}
Thank you for your answer sincerely!
Upvotes: 3
Views: 3018
Reputation: 1640
Use the vast and helpful Qt Event System. That way you can use the same code on Windows as well as Linux.
I would recommend adding a eventFilter
to your application. If the event caught is a QEvent::KeyPress
or QEvent::MouseButtonPress
( or QEvent::MouseButtonDblClick
based on your requirement), take the necessary action.
If the event filter is to be applied for a particular widget in the main window, in the constructor of the main window, add
ui->myWidget->installEventFilter(this);
Now you need to implement the protected method eventFilter
for the main window.
In the header file.
protected:
bool eventFilter(QObject* obj, QEvent* event);
Implementation
bool MainWindow::eventFilter(QObject* obj, QEvent* event)
{
if(event->type() == QEvent::KeyPress)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent *>(event);
qDebug() << "Ate key press " << keyEvent->text();
return true;
}
else if(event->type() == QEvent::MouseButtonPress)
{
qDebug() << "Mouse press detected";
return true;
}
// standard event processing
return QObject::eventFilter(obj, event);
}
It is also possible to filter all events for the entire application, by installing an event filter on the QApplication
or QCoreApplication
object. You can read more on that from the documentation link I provided in the first line.
If the event filter has to be reused, I would recommend adding a dummy class which inherits from QObject
. In this class you can just implement the function eventFilter
. You can now pass an instance of this class to the function installEventFilter
and communicate with the other objects using SIGNALS.
EDIT:
If you are looking to capture events even outside the application, Qt itself does not support that (yet). But you can use the Qxt library that adds support for it using the QxtGlobalShortcut class.
Upvotes: 2