我有一个小问题,我需要将我的事件过滤器设置为QComboBox popup。我需要在按下向左和向右键时捕获事件。我该怎么做呢?
谢谢!
发布于 2012-05-28 22:59:10
您需要在QComboBox的eventFilter () (http://qt-project.org/doc/qt-4.8/qcombobox.html#view)上设置视图。
发布于 2021-11-11 10:40:42
这个问题很古老,但我提供了我的答案,因为它可以帮助其他人。
弹出后,所有事件都将发送到用于QComboBox弹出的列表视图。你可以在列表视图的事件上使用按键处理程序类监视来完成这些工作。
KeyPressHandler.h:
class KeyPressHandler : public QObject
{
Q_OBJECT
public:
explicit KeyPressHandler(QObject *parent = nullptr);
virtual ~KeyPressHandler() override;
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
};KeyPressHandler.cpp:
#include <QCoreApplication>
KeyPressHandler::KeyPressHandler(QObject *parent) : QObject(parent)
{
}
KeyPressHandler::~KeyPressHandler()
{
}
bool KeyPressHandler::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
switch(keyEvent->key())
{
case Qt::Key_Left:
// Send press event for the Key_Up which understood by list view
QCoreApplication::postEvent(obj, new QKeyEvent(QEvent::KeyPress,
Qt::Key_Up,
Qt::NoModifier));
return true;
case Qt::Key_Right:
QCoreApplication::postEvent(obj, new QKeyEvent(QEvent::KeyPress,
Qt::Key_Down,
Qt::NoModifier));
return true;
default:
break;
}
}
// standard event processing
return QObject::eventFilter(obj, event);
}在ComboBox中,当弹出窗口显示时,您将需要安装事件过滤器。它可以通过不同的方式来完成,例如通过覆盖QComboBox::showPopup()函数。
MyComboBox.h.h:
#include <memory>
#include <QComboBox>
class MyComboBox : public QComboBox
{
Q_OBJECT
public:
explicit MyComboBox(QWidget *parent = 0);
protected:
void showPopup() override;
void hidePopup() override;
private:
std::unique_ptr<KeyPressHandler> m_key_press_handler;
};MyComboBox.cpp:
...
void MyComboBox::showPopup()
{
if(!m_key_press_handler)
{
m_key_press_handler.reset(new KeyPressHandler());
QAbstractItemView *v = view();
v->installEventFilter(m_key_press_handler.get());
}
QComboBox::showPopup();
}
void MyComboBox::hidePopup()
{
m_key_press_handler.reset(nullptr);
QComboBox::hidePopup();
}发布于 2012-04-05 15:09:21
您可能需要在代码中的某个位置添加以下代码。
void MyComboBox::keyPressEvent (QKeyEvent *event)
{
if (event->button() == Qt::Key_Left)
{
// handle left key press
}
if (event->button() == Qt::Key_Right)
{
// handle right key press
}
}希望这能有所帮助!
https://stackoverflow.com/questions/10023642
复制相似问题