Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Detect Alt+Enter pressed in QT

Tags:

qt

qt4

I have QTextEdit and i want to detect "Alt+Enter" key is pressed (both keys together). I have installed the Event Filter to detect the key press events and when enter is press i can detect the key, but how do i detect that "Alt" key is also pressed?

I tried to remember the "Alt" key press & release (with static variable) but that does not help if user release the Alt key outside the application.

see attached my code.

bool MTGridEditDelegate::eventFilter(QObject *obj,QEvent *event){
static bool pressed = false;
if(event->type() == QEvent::KeyPress)
{
    if(static_cast<QKeyEvent*>(event)->key() == Qt::Key_Alt)
    {
        pressed = true;
        qDebug("Alt Pressed");
    }
}
if(event->type() == QEvent::KeyRelease)
{
    if(static_cast<QKeyEvent*>(event)->key() == Qt::Key_Alt)
    {
        pressed = false;
        qDebug("Alt Released");
    }
}

if(event->type() == QEvent::KeyPress)
{
    int key = static_cast<QKeyEvent *>(event)->key();
    qDebug("The Key is : %d",key);
    switch (static_cast<QKeyEvent *>(event)->key()) 
    {
        case Qt::Key_Backtab:
            break;
        case Qt::Key_Tab:
        case Qt::Key_Enter:
        case Qt::Key_Return:
        {
            QWidget *editor = ::qobject_cast<QWidget*>(obj);
            if(!pressed)
            {
                emit commitData(editor);
                emit closeEditor(editor, NoHint);
            }
            else
            {
                MQTextEdit *editBox = qobject_cast<MQTextEdit *>(editor);
                if (editBox)
                {
                    QString text = editBox->toPlainText();
                    text = text + QChar('\n');
                    //text = text + QChar('\r');
                    editBox->setPlainText(text);
                }
            }
            break;
        }
        case Qt::Key_Escape:
    //      CustControlFocusLost();
            break;
        default:
            return false;

    }
    return true;
}
else
{
    return QObject::eventFilter(obj,event);
}

}

like image 451
maxchirag Avatar asked Jun 09 '11 12:06

maxchirag


1 Answers

Why don't you use keyPressEvent ?

You need something like this. use the modifiers() method of event.

void myClass::keyPressEvent(QKeyEvent *e)
{
  if ((e->key()==Qt::Key_Return) && (e->modifiers()==Qt::AltModifier))
        doSomething();
}
like image 86
O.C. Avatar answered Oct 13 '22 17:10

O.C.