我使用下面的Qt C++代码定义了一个快捷方式:
QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+Shift+S"), this);
QObject::connect(shortcut, &QShortcut::activated, [=]{qDebug()<<"Example";});如何定义包含多个字母的快捷方式,例如Ctrl+Shift+S+D+F。如果用户按住Ctrl+Shift键并依次按S、D和F键。
注意:我在Linux Ubuntu 20.04中使用Qt 5.15.2。
发布于 2021-01-24 15:40:08
AFAIK,QShortcut目前不支持您所描述的功能。
解决方法是自己安装事件筛选器。
#include <QCoreApplication>
#include <QKeyEvent>
#include <QVector>
class QMultipleKeysShortcut : public QObject
{
Q_OBJECT
public:
explicit inline QMultipleKeysShortcut(const QVector<int> &Keys, QObject *pParent) :
QObject{pParent}, _Keys{Keys}
{
pParent->installEventFilter(this);
}
Q_SIGNALS:
void activated();
private:
QVector<int> _Keys;
QVector<int> _PressedKeys;
inline bool eventFilter(QObject *pWatched, QEvent *pEvent) override
{
if (pEvent->type() == QEvent::KeyPress)
{
if (_PressedKeys.size() < _Keys.size())
{
int PressedKey = ((QKeyEvent*)pEvent)->key();
if (_Keys.at(_PressedKeys.size()) == PressedKey) {
_PressedKeys.append(PressedKey);
}
}
if (_PressedKeys.size() == _Keys.size()) {
emit activated();
}
}
else if (pEvent->type() == QEvent::KeyRelease)
{
int ReleasedKey = ((QKeyEvent*)pEvent)->key();
int Index = _PressedKeys.indexOf(ReleasedKey);
if (Index != -1) {
_PressedKeys.remove(Index, _PressedKeys.size() - Index);
}
}
return QObject::eventFilter(pWatched, pEvent);
}
};和用法:
QMultipleKeysShortcut *pMultipleKeysShortcut = new QMultipleKeysShortcut{{Qt::Key_Control, Qt::Key_Shift, Qt::Key_S, Qt::Key_D, Qt::Key_F}, this};
connect(pMultipleKeysShortcut, &QMultipleKeysShortcut::activated, [=] {qDebug() << "Example"; });https://stackoverflow.com/questions/65867889
复制相似问题