本文介绍了使QSpinBox反应鼠标滚轮事件,当光标不在它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Qt 5.3.2 与 Qt Creator 3.2.1 与 MinGW 4.8.2 在 Windows 7 。我有一个 QSpinBox ,只有当鼠标在 QSpinBox 上时,才可以用鼠标滚轮更改其值。如果鼠标没有超过 QSpinBox ,滚动鼠标滚轮没有效果,即使 QSpinBox 仍然有焦点。我需要做什么,以便能够改变在 QSpinBox 中的重点是鼠标滚轮的值,即使鼠标不悬停在它?设置 mouseTracking 到 true 没有效果。

I am using Qt 5.3.2 with Qt Creator 3.2.1 with MinGW 4.8.2 on Windows 7. I have a QSpinBox and can change its value with the mouse wheel only if the mouse is over the QSpinBox. If the mouse is not over the QSpinBox, scrolling the mouse wheel has no effect, even though the QSpinBox still has focus. What do I need to do to be able to change values in the QSpinBox that has focus with the mouse wheel even if the mouse is not hovering over it? Setting mouseTracking to true does not have that effect.

推荐答案

使用 eventFilter 执行此操作。将它安装到您的 mainWindow :

Use eventFilter to do this. Install it on your mainWindow:

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
        if (obj == this && event->type() == QEvent::Wheel)
        {
            QWheelEvent *wheelEvent = static_cast<QWheelEvent *>(event);
            if(wheelEvent->delta() > 0)
                ui->spinBox->setValue(ui->spinBox->value() + 1);
            else
                ui->spinBox->setValue(ui->spinBox->value() - 1);
        }
}

这只是一个例子,你要。

It is just example, so you can improve it as you want.

或使用:

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{

        if (obj == this && event->type() == QEvent::Wheel)
        {
            QApplication::sendEvent(ui->spinBox,event);
        }
}

在此示例中,

但不要忘记

protected:
bool eventFilter(QObject *obj, QEvent *event);//in header

qApp->installEventFilter(this);//in constructor

建议使用 DmitrySazonov 。我们将检测wheelEvents当我们的spinBox在焦点,当spinBox losed焦点,我们不反应轮(其他小部件反应正常)。我们这样做在一个eventFilter。为此,提供新的bool变量。例如:

As DmitrySazonov recommended. We will detect wheelEvents when our spinBox in focus, when spinBox losed focus, we don't react on wheel(other widgets react normal). We do this in one eventFilter. To do this provide new bool variable. For example:

private:
bool spin;//in header

在构造函数中初始化它:

Initialize it in constructor:

spin = false;

您的eventFilter应该是

And your eventFilter should be.

    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
    {
        if(obj == ui->spinBox && event->type() == QEvent::FocusIn)
            spin = true;


        if(spin)
        {
            if (obj == this && event->type() == QEvent::Wheel)
            {
                QApplication::sendEvent(ui->spinBox,event);
            }
        }

        if(obj == ui->spinBox && event->type() == QEvent::FocusOut)
            spin = false;
    }

还可以这样做,不需要额外的变量:

Or do just this, without additional variable:

if (obj == this && event->type() == QEvent::Wheel)
{
    if(ui->spinBox->hasFocus())
        QApplication::sendEvent(ui->spinBox,event);
}

这篇关于使QSpinBox反应鼠标滚轮事件,当光标不在它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 20:58