I'm trying to install eventFilter
on QComboBox
but the function isn't getting triggered
Header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
bool eventFilter(QObject *obj, QEvent *event);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
Source:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->comboBox->installEventFilter(ui->comboBox);
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
QComboBox* combo = qobject_cast<QComboBox*>(obj);
if(combo)
{
if(event->type() == QEvent::Wheel)
{
if(combo->focusPolicy() == Qt::WheelFocus)
{
event->accept();
return false;
}
else
{
event->ignore();
return true;
}
}
else if(event->type() == QEvent::FocusIn)
{
combo->setFocusPolicy(Qt::WheelFocus);
}
else if(event->type() == QEvent::FocusOut)
{
combo->setFocusPolicy(Qt::StrongFocus);
}
}
return QObject::eventFilter(obj, event);
}
UI:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget name="centralwidget">
<widget name="comboBox">
<property name="geometry">
<rect>
<x>220</x>
<y>240</y>
<width>241</width>
<height>22</height>
</rect>
</property>
<item>
<property name="text">
<string>A</string>
</property>
</item>
<item>
<property name="text">
<string>B</string>
</property>
</item>
<item>
<property name="text">
<string>C</string>
</property>
</item>
<item>
<property name="text">
<string>D</string>
</property>
</item>
<item>
<property name="text">
<string>E</string>
</property>
</item>
<item>
<property name="text">
<string>F</string>
</property>
</item>
<item>
<property name="text">
<string>G</string>
</property>
</item>
<item>
<property name="text">
<string>H</string>
</property>
</item>
</widget>
</widget>
<widget name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>21</height>
</rect>
</property>
</widget>
<widget name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
CodePudding user response:
You need to pass this operator to installEventFilter
ui->comboBox->installEventFilter(this);
and use virtual and override keyword for eventFilter function
virtual bool eventFilter(...) override;