c++ - 在 Qt C++ 中定义多个字母的快捷方式
问题描述
我使用以下 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。
解决方案
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"; });
推荐阅读
- python-3.x - 将图像数据集拆分为训练测试数据集
- vb.net - Renci.SshNet由于错误无法连接
- data-structures - 是否有除堆栈以外的数据结构用于字符串反转?
- xamarin.forms - 如何自动播放 xamarin 表单中的图像列表
- python - 为什么我的变量在使用 pop() 方法时没有更新?
- javascript - 反应箭头功能组件 - 未定义 setState
- java - 无法在 java 程序中导入 RClusteredMap
- pdf - 在保留页面的同时在 Chromium 中重新加载 PDF
- django - AttributeError:“CreateBatchForm”对象没有属性“get”
- spring-security - 使用 X509 的 SpringOauth 令牌