QKeySequence::toString(): Treat Modifier+Qt::Key_Unknown as empty string

We were already doing this for a key combination without modifiers,
but now we do the same for e.g. Control+Unknown. This matches the
behavior we have for QKeySequencePrivate::decodeString(), where
we return Qt::Key_Unknown if we can't resolve the key, even if
we have resolved some valid modifiers, e.g. "Meta+Trolls" as in
the tst_QKeySequence::parseString() test.

Change-Id: I238e29276e6ce356ae60c67585739587fa388f07
Reviewed-by: Liang Qi <liang.qi@qt.io>
bb10
Tor Arne Vestbø 2023-10-06 16:07:09 +02:00
parent e4994ccfe0
commit ab99cf6077
2 changed files with 4 additions and 3 deletions

View File

@ -1203,10 +1203,10 @@ QString QKeySequencePrivate::encodeString(QKeyCombination keyCombination, QKeySe
bool nativeText = (format == QKeySequence::NativeText);
QString s;
int key = keyCombination.toCombined();
const auto key = keyCombination.key();
// Handle -1 (Invalid Key) and Qt::Key_unknown gracefully
if (key == -1 || key == Qt::Key_unknown)
if (keyCombination.toCombined() == -1 || key == Qt::Key_unknown)
return s;
const auto modifiers = keyCombination.keyboardModifiers();
@ -1253,7 +1253,7 @@ QString QKeySequencePrivate::encodeString(QKeyCombination keyCombination, QKeySe
if (modifiers & Qt::KeypadModifier)
addKey(s, nativeText ? QCoreApplication::translate("QShortcut", "Num") : QString::fromLatin1("Num"), format);
QString keyName = QKeySequencePrivate::keyName(keyCombination.key(), format);
QString keyName = QKeySequencePrivate::keyName(key, format);
#if defined(Q_OS_APPLE)
if (nativeText)

View File

@ -473,6 +473,7 @@ void tst_QKeySequence::toStringFromKeycode_data()
QTest::newRow("A") << QKeySequence(Qt::Key_A) << "A";
QTest::newRow("-1") << QKeySequence(-1) << "";
QTest::newRow("Unknown") << QKeySequence(Qt::Key_unknown) << "";
QTest::newRow("Ctrl+Unknown") << QKeySequence(Qt::ControlModifier | Qt::Key_unknown) << "";
QTest::newRow("Ctrl+Num+Ins") << QKeySequence(Qt::ControlModifier | Qt::KeypadModifier | Qt::Key_Insert) << "Ctrl+Num+Ins";
QTest::newRow("Ctrl+Num+Del") << QKeySequence(Qt::ControlModifier | Qt::KeypadModifier | Qt::Key_Delete) << "Ctrl+Num+Del";
QTest::newRow("Ctrl+Alt+Num+Del") << QKeySequence(Qt::ControlModifier | Qt::AltModifier | Qt::KeypadModifier | Qt::Key_Delete) << "Ctrl+Alt+Num+Del";