Qt/C++ - Tutorial 077. QComboBox - ignoring hidden items in the drop-down list when scrolling

QComboBox, Qt, eventFilter

In one of the previous articles, it was shown how to hide some items in the QComboBox drop-down list so that the user could not select them. However, I did not pay attention to the fact that if the user hovers the mouse on the combo box itself and scrolls the mouse wheel, it can select this hidden menu item. Therefore, this behavior should be prohibited.

You can do this with the help of the mouse scrolling event scrolling within this combo box.

Depending on the structure of the program, you can do this in two ways:

  1. Inherit from the QComboBox class and override the method wheelEvent(QWheelEvent * event ).
  2. Inherit from the QObject class and override the method eventFilter(QObject* obj , QEvent * event )

By itself, the main code of the method will be similar in both cases, there will be different locations of this code. This will be determined by whether you need to create a QComboBox custom class or not.

With inheritance from QComboBox

When inheriting from QComboBox , we override the wheelEvent(QWheelEvent* event) method and check which of the lines are hidden. We will ignore all hidden lines at the event of the scratch and jump to the next available visible line.

void CustomComboBox::wheelEvent(QWheelEvent* event)
{
    int row = this->currentIndex();
    int count = this->count();
    QListView* dropdownList = static_cast<QListView*>(this->view());

    do
    {
        event->angleDelta().y() < 0 ? ++row : --row;
        if (row >= 0 && row < count && !dropdownList->isRowHidden(row))
        {
            this->setCurrentIndex(row);
            return;
        }
    }
    while (row >= 0 && row < count);
}

With the filter installed

If you do not want to create a custom QComboBox , but you need this functionality, then you can create a filter in that window (all widgets are inherited from QObject), where your QComboBox is installed.

To do this, we redefine the window method eventFilter(QObject* obj , QEvent * event ).

bool Widget::eventFilter(QObject* obj, QEvent *event)
{
    if (event->type() == QEvent::Wheel)
    {
        QWheelEvent *wheelEvent = static_cast<QWheelEvent*>(event);
        QComboBox* comboBox = static_cast<QComboBox*>(obj);

        int row = comboBox->currentIndex();
        int count = comboBox->count();
        QListView* dropdownList = static_cast<QListView*>(comboBox->view());

        do
        {
            wheelEvent->angleDelta().y() < 0 ? ++row : --row;
            if (row >= 0 && row < count && !dropdownList->isRowHidden(row))
            {
                comboBox->setCurrentIndex(row);
                return true;
            }
        }
        while (row >= 0 && row < count);

        return true;
    }

    return QObject::eventFilter(obj, event);
}

and install this filter on the target QComboBox

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->comboBox->installEventFilter(this); // Установим фильтр
}
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

DP
Oct. 19, 2019, 1:45 a.m.
Dmitrij Pasynkov

C++ - Test 001. The first program and data types

  • Result:26points,
  • Rating points-10
AS
Oct. 18, 2019, 1:27 p.m.
Artem Sergeevich

C++ - Test 001. The first program and data types

  • Result:13points,
  • Rating points-10
MB
Oct. 18, 2019, 11:05 a.m.
Mihail Bulatov

C++ - Test 001. The first program and data types

  • Result:86points,
  • Rating points6
Last comments
Oct. 17, 2019, 2:17 a.m.
Evgenij Legotskoj

Используем, там где требуется :)
MP
Oct. 17, 2019, 2:15 a.m.
Mikhail Petrov

Совет: подключайте ресурсы динамически. Используйте Resource Compiler: https://doc.qt.io/qt-5/rcc.html
Oct. 16, 2019, 6:45 a.m.
Evgenij Legotskoj

Если это не чистой воды спам, а по делу, то без проблем. Но в таком случае лучше создавайте отдельный вопрос на форуме . При создании вопроса есть поле, в котором можно указать статью…
KK
Oct. 16, 2019, 6:39 a.m.
Kirill Kirilych

А тут можно ссылки на сторонний ресурс показывать? Нашёл на habr похожую статью, только там чуток отличается код и про локальный сервер написано, нужно чтоб кто то понимающий посмотрел и своё …
Now discuss on the forum
Oct. 18, 2019, 1:30 p.m.
Evgenij Legotskoj

Добрый день. У вас там пробелы находятся в тексте, поэтому и не может сконвертировать. фукция map применяет float ко все символам в каждой строке. В том числе и к символам пробела. А пробе…
Oct. 17, 2019, 10:31 a.m.
Ruslan Volshebnik

Я вас понял) Спасибо ещё раз. Вы помогли мне во всём разобраться.
t
Oct. 17, 2019, 4:13 a.m.
tupo_chel

И тебе спасибо за помощь)
Oct. 17, 2019, 2:14 a.m.
Evgenij Legotskoj

Добрый день. Ну да, этот вариант жизнеспособен. Есть только один момент, который вам необходимо понимать в данном случае. И чего в этой статье или нет, или сказано как-то совсем вскользь, …
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB