How can I capture QKeySequence from QKeyEvent depending on current keyboard layout?

后端 未结 7 1523
一向
一向 2020-12-09 12:05

I need to do this for configuring my application. I have QLineEdit field with reimplemented keyPressEvent method.

QKeyEvent *ke = ...
QString txt;

if(ke->         


        
7条回答
  •  误落风尘
    2020-12-09 12:25

    What you might find very useful is the function QKeySequence().toString().

    The following is a part of a code that I use to capture User Defined Shortcuts. With some modifications it can do whatever you need in your project. Hope it helps (sorry for the crapped identation):

    if (event->type() == QEvent::KeyPress){ 
        QKeyEvent *keyEvent = static_cast(event); 
    
        int keyInt = keyEvent->key(); 
        Qt::Key key = static_cast(keyInt); 
        if(key == Qt::Key_unknown){ 
            qDebug() << "Unknown key from a macro probably"; 
            return; 
        } 
        // the user have clicked just and only the special keys Ctrl, Shift, Alt, Meta. 
        if(key == Qt::Key_Control || 
            key == Qt::Key_Shift || 
            key == Qt::Key_Alt || 
            key == Qt::Key_Meta)
        { 
            qDebug() << "Single click of special key: Ctrl, Shift, Alt or Meta"; 
            qDebug() << "New KeySequence:" << QKeySequence(keyInt).toString(QKeySequence::NativeText); 
            return; 
        } 
    
        // check for a combination of user clicks 
        Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); 
        QString keyText = keyEvent->text(); 
        // if the keyText is empty than it's a special key like F1, F5, ... 
        qDebug() << "Pressed Key:" << keyText; 
    
        QList modifiersList; 
        if(modifiers & Qt::ShiftModifier) 
            keyInt += Qt::SHIFT; 
        if(modifiers & Qt::ControlModifier) 
            keyInt += Qt::CTRL; 
        if(modifiers & Qt::AltModifier) 
            keyInt += Qt::ALT; 
        if(modifiers & Qt::MetaModifier) 
            keyInt += Qt::META; 
    
        qDebug() << "New KeySequence:" << QKeySequence(keyInt).toString(QKeySequence::NativeText); 
    }
    

提交回复
热议问题