尝试使用QObject::installEventFilter
例如
QtStackOverflow.h
#pragma once
#include <QtWidgets/QMainWindow>
#include <QToolButton>
#include "ui_QtStackOverflow.h"
class QtStackOverflow : public QMainWindow
{
Q_OBJECT
public:
QtStackOverflow(QWidget *parent = Q_NULLPTR);
private:
Ui::QtStackOverflowClass ui;
};
class KeyPressEater : public QObject
{
Q_OBJECT
public:
KeyPressEater(QToolButton*btn) : keyOtherPush(false), keyAltPush(false) { _btn = btn; }
protected:
bool eventFilter(QObject *obj, QEvent *event);
private:
QToolButton * _btn;
bool keyOtherPush;
bool keyAltPush;
};
主.cpp
#include "QtStackOverflow.h"
#include <QtWidgets/QApplication>
#include <QObject>
#include <QEvent>
#include <QKeyEvent>
#include <QLabel>
#include <QMainWindow>
#include <QMenu>
#include <QShortcut>
#include <QToolButton>
#include <QVBoxLayout>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow w;
auto label = new QLabel();
auto menu = new QMenu(&w);
// intentionally added a shortcut which contains Alt as modifier to test it does not interfere with the menu
int number = 0;
menu->addAction("Action", [label, &number] {
label->setText(QString("%1 %2 ").arg("Trigered!").arg(number));
number++;
}, QKeySequence("Alt+Left"));
auto btn = new QToolButton();
btn->setMenu(menu);
btn->setPopupMode(QToolButton::InstantPopup);
// the following lines do not have any effect, the menu is not shown when Alt is pressed and released
auto shortcut = new QShortcut(QKeySequence(Qt::Key_Alt), &w);
QObject::connect(shortcut, &QShortcut::activated, btn, &QToolButton::showMenu);
KeyPressEater *m_keyPressEater;
m_keyPressEater = new KeyPressEater(btn);
qApp->installEventFilter(m_keyPressEater);
auto container = new QWidget();
auto layout = new QVBoxLayout(container);
layout->addWidget(btn);
layout->addWidget(label);
w.setCentralWidget(container);
w.show();
return a.exec();
}
bool KeyPressEater::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{
int key = static_cast<QKeyEvent *>(event)->key();
if (key == Qt::Key_Alt)
{
keyAltPush = true;
}
else {
keyOtherPush = true;
}
return QObject::eventFilter(obj, event);
}
else if (event->type() == QEvent::KeyRelease)
{
int key = static_cast<QKeyEvent *>(event)->key();
if (key == Qt::Key_Alt) {
if (keyAltPush == true && keyOtherPush == false) {
_btn->showMenu();
}
}
else {
keyAltPush = false;
keyOtherPush = false;
}
return true;
}
else {
return QObject::eventFilter(obj, event);
}
}
在这种情况下,你将得到所有的按键在任何时候。
然后需要检查QObject*senderObj=sender()