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);
}
}
开发者_如何学Gobreak;
}
case Qt::Key_Escape:
// CustControlFocusLost();
break;
default:
return false;
}
return true;
}
else
{
return QObject::eventFilter(obj,event);
}
}
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();
}
精彩评论