简体   繁体   中英

QLineEdit could not set shortcuts when it's in focus

I'm implementing a text-based to-do program. I have a CommandInput widget which inherits from QLineEdit . Basically there are a few commands, starting with keywords "add", "delete", "edit", and a few more.

I want to implement a few shortcuts.

  1. Ctrl+A so that when the widget has focus, I can setText("add \"\"") , cursor at the second last position, so it appears to be add "|"
  2. Tab so that when the widget has focus, when the user types in the first keyword, for example, add , then I can complete the command to add "|"

The key problem is that when the widget has focus, the shortcuts are not working. I've tried the following ways:

1/ Override keyPressEvent . The Tab key does not work as intended. And even if it works, I don't know how to do that for a keySequence like Ctrl+A .

void CommandInput::keyPressEvent(QKeyEvent *keyEvent)

{
    switch(keyEvent->key())
    {
    case Qt::Key_Tab;
        emit add_activated();
    default:
        QLineEdit::keyPressEvent(keyEvent);
    }
}

2/ Create shortcuts when initializing. This doesn't work either.

CommandInput::CommandInput(QWidget *parent)
    : QLineEdit(parent)
{
    tab_shortcut = new QShortcut(QKeySequence("Tab"),this);
    add_shortcut = new QShortcut(QKeySequence("Ctrl+A"),this);

    connect(tab_shortcut, SIGNAL(activated()),
            this, SIGNAL(tab_activated()));
    connect(add_shortcut, SIGNAL(activated()),
            this, SIGNAL(add_activated()));
}

Hope you could help me on this issue. Thanks!

Overriding keyPressEvent is probably the preferred approach here. I'm going to guess that the reason why "Tab" doesn't work as expected is because you don't have a break statement after emitting add_activated() . For "Ctrl+A", you'll have to look at the modifiers() for the key event. As such, your keyPressEvent would look something like this:

void CommandInput::keyPressEvent(QKeyEvent* keyEvent)
{
   if (keyEvent->key() == Qt::Key_Tab)
   {
      emit add_activated();
   }
   else if (keyEvent->key() == Qt::Key_A && 
            keyEvent->modifiers() == Qt::ControlModifier)
   {
      // Code for Ctrl+A goes here.
   }
   else
   {
      QLineEdit::keyPressEvent(keyEvent);
   }
}

This seems to work on my (Linux) machine.

In order to get the Tab key working, I had to catch the keyPressEvent within event(), like this:

bool MyQTextBox::event(QEvent* event) {
    if (event->type() == QEvent::KeyPress) { // this did the trick for me
        this->keyPressEvent(dynamic_cast<QKeyEvent*>(event));
        return true;
    }
    return QWidget::event(event);
}

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