I want to track when the enter/return key is pressed and then to focus on some other widget but if it's not pressed than spinbox should take normal action instead of anything else. I've subclassed QSpinBox and created protected void keyPressEvent(QKeyEvent *event). Inside it is this code:

void MytSpinBox::keyPressEvent(QKeyEvent *event) {
    if (event->key() == Qt::Key_Return) {
        qDebug() << "return pressed";
        editingFinished();
    } else {
        qDebug() << "Other key";
        event->accept();
    }
}

This code should work, but it doesn't. I don't know what's wrong, but when I focus on promoted spinbox and try to change number in it, it just won't work, I only get the debug message printed. If I push enter/return key than it print debug message and focus on some other widget which I set in editingFinished().

What am I doing wrong?

有帮助吗?

解决方案

If you need to invoke default processing of the event, you need to call base class implementation:

void MytSpinBox::keyPressEvent(QKeyEvent *event) {
    if (event->key() == Qt::Key_Return) {
        qDebug() << "return pressed";
        editingFinished();
    } else {
        QSpinBox::keyPressEvent(event);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top