简体   繁体   中英

Implementing Backspace and Enter Keys on a Qt Virtual Keyboard

I'm implementing a virtual keyboard as in input panel widget based on the example here . I've able to have characters appear in a text widget by emitting a signal like so emit characterGenerated( char ) -- please refer to buttonClicked(QWidget *w) method in the example . Unfortunately this approach does not work for the enter and backspace keys. I'd appreciate advise on possible workarounds.

If it matters, I'm developing in C++.

Consider MyInputPanelContext::sendCharacter function in the linked example. When QKeyEvent keyPress object is constructed, character.unicode() is used as the second argument. However, you can also use Qt::Key values as the second argument. For example:

QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Backspace, Qt::NoModifier);

You should rewrite this method to accept int argument that will be passed to QKeyEvent constructor and change characterGenerated(QChar) signal to keyGenerated(int) so you can send a special key ( Qt::Key_Backspace ) or a character key ( character.unicode() ) using the same signal and slot.

This one is specific to that example. I turned '*' button to backspace by modifying sendcharacter code (in myinputpanelcontext.cpp) to this. Please have a look. Hope it helps.

void MyInputPanelContext::sendCharacter(QChar character)
{
     QPointer<QWidget> w = focusWidget();

     if (!w)
         return;

     QKeyEvent keyPress(QEvent::KeyPress, character.unicode(), Qt::NoModifier, QString(character));
     QKeyEvent keybkspc(QEvent::KeyPress, Qt::Key_Backspace, Qt::NoModifier);

     if(character != '*')
     {
        QApplication::sendEvent(w, &keyPress);
     }
     else
     {
         QApplication::sendEvent(w, &keybkspc);
     }
     if (!w)
         return;

     QKeyEvent keyRelease(QEvent::KeyPress, character.unicode(), Qt::NoModifier, QString());
     QApplication::sendEvent(w, &keyRelease);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM