I found a few alternative ways to achieve my requirement. I want a QLineEdit
like input field, which will capture key combinations that adhere to following formats:
- Alt+Ctrl+Shift+X
- Alt+Ctrl+X
- Alt+Shift+X
- Ctrl+Shift+X
The easiest way to do this is by sub-classing QLineEdit
& re-implementing keyPressEvent( QKeyEvent * event )
function. My header file and cpp file look like this. Anyone can manipulate the logic inside keyPressEvent
to suit their requirement.
QLineEditHotKey.h
#include <QLineEdit>
class QLineEditHotKey: public QLineEdit
{
public:
QLineEditHotKey( QWidget* pParent = NULL);
~QLineEditHotKey(){}
protected:
void keyPressEvent ( QKeyEvent * event );
};
QLineEditHotKey.cpp
QLineEditHotKey::QLineEditHotKey(QWidget* pParent):QLineEdit(pParent)
{
}
void QLineEditHotKey::keyPressEvent( QKeyEvent * event )
{
int keyInt = event->key();
Qt::Key key = static_cast<Qt::Key>(keyInt);
// Handle unknown keys
if( key == Qt::Key_unknown )
return;
// Pressing Esc or Backspace will clear the content
if( key == Qt::Key_Escape || key == Qt::Key_Backspace )
{
setText(NULL);
return;
}
// Empty means a special key like F5, Delete, Home etc
if( event->text().isEmpty() )
return;
// Checking for key combinations
Qt::KeyboardModifiers modifiers = event->modifiers();
if(modifiers.testFlag(Qt::NoModifier))
return;
if(modifiers.testFlag(Qt::ShiftModifier))
keyInt += Qt::SHIFT;
if(modifiers.testFlag(Qt::ControlModifier))
keyInt += Qt::CTRL;
if(modifiers.testFlag(Qt::AltModifier))
keyInt += Qt::ALT;
setText( QKeySequence(keyInt).toString(QKeySequence::NativeText) );
}
This question was very helpful in finding the solution.