Ignore mouse and keyboard events in Qt

随声附和 提交于 2020-01-01 02:34:08

问题


In Qt, how can I ignore all mouse and keyboard events and later stop ignoring them? That is: click a button, ignore all events in children; click again, not ignore. Is that clear? I have the following lines, but maybe I'm doing something wrong:

setAttribute(Qt::WA_TransparentForMouseEvents);

setFocusPolicy(Qt::NoFocus);

回答1:


Dont use setFocusPolicy(Qt::NoFocus); and it will propagate events to the parent. Use only setAttribute(Qt::WA_TransparentForMouseEvents);




回答2:


You can use Events' filters on your mouse and keyboard events to filter some keypress or mouseclick when you need so :

yourWidget->installEventFilter(this);

...

bool YourFrm::eventFilter(QObject* pObject, QEvent* pEvent)
{
    if (pEvent->type() == QEvent::KeyPress) 
    {
        QKeyEvent* pKeyEvent = static_cast<QKeyEvent*>(pEvent);
        int PressedKey = pKeyEvent->key();

        if(PressedKey == Qt::Key_Return)
        {
            // Filter Return key....
            return true;
        }

        // standard event processing
        return QObject::eventFilter(pObject, pEvent);
    }
    else if (pEvent->type() == QEvent::MouseButtonPress) 
    {
        QMouseEvent* pMouseEvent = static_cast<QMouseEvent*>(pEvent);

        ... // etc...
    }
    else 
    {
        // standard event processing
        return QObject::eventFilter(pObject, pEvent);
    }
}

More informations on this : http://qt.nokia.com/doc/4.6/eventsandfilters.html

Hope it helps !




回答3:


You could use:

QWidget::setEnabled(false)

it disable mouse and keyboard events for a widget.




回答4:


Do you mean for a QGraphicsItem ?

If yes, you can call

void QGraphicsItem::setEnabled ( bool enabled )

And to activate the event later, as the item doesn't receive events any more, you have to pass by the Scene, because you can't receive directly event on the item.
If your problem is not using GraphicsView Frameworks, but other part of qt, it's almost the same process :
You can call :

QWidget::setEnabled(false) //like Massimo said

In order to reactive the widget, just detect press event inside an object in your application to be able to call `setEnable(true) on your widget !

Hope it helps ! `



来源:https://stackoverflow.com/questions/2203698/ignore-mouse-and-keyboard-events-in-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!