如何使用Qt在linux平台上侦听全局鼠标和键盘事件?

如何使用Qt在linux平台上侦听全局鼠标和键盘事件?,qt,mouseevent,keyboard-events,Qt,Mouseevent,Keyboard Events,我使用Qt开发我的应用程序,我想监听全局鼠标和键盘事件,这样我可以在检测到这些事件后做些事情。在windows平台上,我使用SetWindowsHookExAPI。但我不知道如何在Linux上做类似的事情 我在Windows上的代码如下所示: /*********************listen mouse event*****************************/ mouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, NULL

我使用Qt开发我的应用程序,我想监听全局鼠标和键盘事件,这样我可以在检测到这些事件后做些事情。在windows平台上,我使用SetWindowsHookExAPI。但我不知道如何在Linux上做类似的事情

我在Windows上的代码如下所示:

/*********************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";
}
/****************侦听鼠标事件*****************************/
mouseHook=SetWindowsHookEx(WH_MOUSE_LL,mouseProc,NULL,0);
if(mouseHook==NULL){
qDebug()使用大量有用的代码。这样,您就可以在Windows和Linux上使用相同的代码

我建议在应用程序中添加
eventFilter
。如果捕获的事件是
QEvent::KeyPress
QEvent::MouseButtonPress
(或
QEvent::mousebuttondblick
),请根据需要采取必要的措施

如果要为主窗口中的特定小部件应用事件过滤器,请在主窗口的构造函数中添加

ui->myWidget->installEventFilter(this);
现在需要为主窗口实现受保护的方法
eventFilter

在头文件中

protected:
    bool eventFilter(QObject* obj, QEvent* event);
实施

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);
}
bool主窗口::事件过滤器(QObject*obj,QEvent*event)
{
如果(事件->类型()==QEvent::按键)
{
QKeyEvent*keyEvent=静态广播(事件);
qDebug()类型()==QEvent::MouseButtonPress)
{

qDebug()我相信他想要听应用程序之外的事件。@thuga:看这个问题,我的印象是他只想对应用程序内的事件采取行动。让我编辑我的答案以包括系统范围的事件。:)