在激活快捷方式之前,焦點窗口小部件會被指定一個ShortcutOverride事件。如果事件被接受,則關鍵事件被傳遞給小部件,並且快捷方式未被激活。
來源:https://wiki.qt.io/ShortcutOverride
看着Qt的源
QAbstractSpinBox::event(QEvent *event)
{
Q_D(QAbstractSpinBox);
switch (event->type()) {
...
case QEvent::ShortcutOverride:
if (d->edit->event(event))
return true;
break;
...
}
return QWidget::event(event);
}
QAbstractSpinBox被允許內部編輯接受該事件。 QLineEdit遵循QLineControl。來自qt/src/gui/widgets/qlinecontrol.cpp
case QEvent::ShortcutOverride:{
if (isReadOnly())
return false;
QKeyEvent* ke = static_cast<QKeyEvent*>(ev);
if (ke == QKeySequence::Copy
|| ke == QKeySequence::Paste
|| ke == QKeySequence::Cut
|| ke == QKeySequence::Redo
|| ke == QKeySequence::Undo
|| ke == QKeySequence::MoveToNextWord
|| ke == QKeySequence::MoveToPreviousWord
|| ke == QKeySequence::MoveToStartOfDocument
|| ke == QKeySequence::MoveToEndOfDocument
|| ke == QKeySequence::SelectNextWord
|| ke == QKeySequence::SelectPreviousWord
|| ke == QKeySequence::SelectStartOfLine
|| ke == QKeySequence::SelectEndOfLine
|| ke == QKeySequence::SelectStartOfBlock
|| ke == QKeySequence::SelectEndOfBlock
|| ke == QKeySequence::SelectStartOfDocument
|| ke == QKeySequence::SelectAll
|| ke == QKeySequence::SelectEndOfDocument) {
ke->accept();
} else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier
|| ke->modifiers() == Qt::KeypadModifier) {
if (ke->key() < Qt::Key_Escape) {
ke->accept();
} else {
switch (ke->key()) {
case Qt::Key_Delete:
case Qt::Key_Home:
case Qt::Key_End:
case Qt::Key_Backspace:
case Qt::Key_Left:
case Qt::Key_Right:
ke->accept();
default:
break;
}
}
}
}
如果還沒有按下控制鍵,則此代碼接受大多數鍵。
所以最簡單的解決方案是更改快捷方式以包含控件修飾符。
或者,你也可以繼承的旋轉框和重載事件函數
bool MySpinBox::event(QEvent *event)
{
if(event->type() == QEvent::ShortcutOverride && !isReadOnly())
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
// Ignore 'B' shortcuts
if(keyEvent->key() == Qt::Key_B)
{
Q_ASSERT(!event->isAccepted());
return true;
}
return QSpinBox::event(event);
}
謝謝您的回答。你可能有任何想法如何解決這個問題?我的意思是如何在每次「點擊」後自動從QSpinBox中刪除keyboard_focus? – Marwroc 2011-04-12 18:33:18
@Marwroc我更新了答案。你嘗試過'QShortcut :: setContext'嗎? – 2011-04-12 18:35:11
是的,我已經嘗試了這兩個選項,但它仍然不起作用; /我讀了一些關於setFocusPolicy(),但我不確定如何使用它,如果它是解決方案。 – Marwroc 2011-04-12 18:43:31