QComboBox事件过滤器弹出
QComboBox EventFilter to popup
我有一个小问题,我需要将我的事件过滤器设置为QComboBox弹出窗口。当按下左右键时,我需要捕捉事件。我该怎么做?
谢谢!
您需要在QComboBox的视图()上设置eventFilter(http://qt-project.org/doc/qt-4.8/qcombobox.html#view)。
您可能需要在代码中添加以下代码。
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
}
}
希望这能有所帮助!
这个问题很老了,但我提供了我的答案,因为它可以帮助其他人。
弹出后,所有事件将被发送到用于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);
}
在组合框中,当弹出窗口显示时,您需要安装事件过滤器。它可以通过不同的方式完成,例如通过重写 QComboBox::showPopup()
函数。
MyComboBox.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();
}
相关文章:
- Android NDK传感器向事件队列报告奇怪的间隔
- 带过滤器的现代迭代c++集合
- 从文本文件中读取时钟时间和事件时间并进行处理
- WMI检测进程创建事件-c++
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 在事件过滤器之前发出对象的事件
- Qt:事件过滤器在显示 QCompleter 时不接收按键
- Qt 中的去抖动事件过滤器
- QT 事件过滤器 mouseEvent->pos().x() 始终为零,但 mouseEvent->pos().y() 工作正常
- 按键事件过滤器出现问题
- 为 QAbstractScrollArea 安装事件过滤器
- QwidgetWindow作为QT5的事件过滤器中的QObject
- 使用QComboBox的过滤器小部件
- Qt 事件过滤器未检测到对象名称
- 如何在事件过滤器中相互更改Left_Key和Right_Key事件
- Qt、多重继承、包装器或事件过滤器
- QComboBox事件过滤器弹出
- 在QScrollArea视图上安装事件过滤器
- 是否有一种方法来卸载事件过滤器在qt
- QML 中的事件过滤器