禁用QSpinBox中的滚轮

3

我在我的PySide项目中有许多旋转框,我希望更改它们的行为,以便用户需要单击字段才能更改值,然后按下回车键。我希望禁用旋转框的滚动轮行为。我已经尝试设置焦点策略,但它没有生效。

    def light_label_event(self,text,checked):
        print("this is the pressed button's label", text)

    def populate_lights(self):
        for light in self.lights:
            light_label = QtWidgets.QSpinBox()
            light_label.setFocusPolicy(QtCore.Qt.StrongFocus)
3个回答

4

你需要创建一个自定义的SpinBox并覆盖wheelEvent方法:

from PySide2 import QtWidgets


class SpinBox(QtWidgets.QSpinBox):
    def wheelEvent(self, event):
        event.ignore()

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = SpinBox()
    w.show()
    sys.exit(app.exec_())

3

您也可以覆盖现有小部件的mouseEvent。例如,如果您想忽略特定spinbox中的滚动事件,您可以使用lambda函数覆盖wheelEvent,使其不执行任何操作:

from PyQt5 import QtWidgets

box = QtWidgets.QSpinBox()
box.wheelEvent = lambda event: None

或者,您可以使用findChildren函数来更改主窗口包含的特定类型(例如QSpinBox)的所有小部件的事件,如下所示:

from PyQt5 import QtCore, QtWidgets

main = QtWidgets.QMainWindow()

'''add some QSpinboxes to main'''

opts = QtCore.Qt.FindChildrenRecursively
spinboxes = main.findChildren(QtWidgets.QSpinBox, options=opts)
for box in spinboxes:
    box.wheelEvent = lambda *event: None

理论上,这个原则也可以应用于其他小部件类和事件,但我还没有测试过除了旋转框和滚轮事件之外的内容。


谢谢,非常有用的答案。 - Elan

0

还可以将IgnoreWheelEvent类实现为事件过滤器。该类必须实现eventFilter(QObject, QEvent)。然后,您可以执行spinBox.installEventFilter(IgnoreWheelEvent)

我最近在C++中实现了这个功能。因为我不想发布可能有误的Python代码,所以这里是我的C++实现,以便您了解。我已经在构造函数中执行了installEventFilter,这样可以节省一行代码。

class IgnoreWheelEventFilter : public QObject
{
    Q_OBJECT
public:
    IgnoreWheelEventFilter(QObject *parent) : QObject(parent) {parent->installEventFilter(this);}
protected:
    bool eventFilter(QObject *watched, QEvent *event) override
{
    if (event->type() == QEvent::Wheel)
    {
        // Ignore the event
        return true;
    }
    return QObject::eventFilter(watched, event);
}
};

//And later in the implementation...
IgnoreWheelEventFilter *ignoreFilter = new IgnoreWheelEventFilter(ui->spinBox);
// And if not done in the constructor:
// ui->spinBox->installEventFilter(ignoreFilter);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接