[Python] Horizontal scroll on shift in PyQt

Discussão em 'Python' iniciado por Stack, Julho 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have a PyQt6 Application in which I have multiple QTextEdits, which contain text that sometimes overflow the visible range of the lines. Using the combination of Shift+Mouse-Wheel, my goal was to have it then scroll vertically.

    Now to be able to scroll horizontally I tried to implement an eventFilter that detects the keypress Shift and then converts the wheel movement into a horizontal movement. For clarification: Additionally, because I also wanted to be able to scroll when I am only hovering over it like the normal behavior of vertical scrolling works, I added a while loop to find the actual QTextEdit within the returned anonymous widget (-reference) from QApplication.widgetAt. I figured that this would be a better approach instead of generating a list of all the QTextEdit references and comparing it against the returned reference.

    def eventFilter(self, obj, event):
    if isinstance(event, QWheelEvent) and QApplication.keyboardModifiers() == Qt.KeyboardModifier.ShiftModifier:
    widget_under_mouse = QApplication.widgetAt(event.globalPosition().toPoint())
    while widget_under_mouse is not None:
    if isinstance(widget_under_mouse, QTextEdit): break
    widget_under_mouse = widget_under_mouse.parent() # Move up in the hierarchy

    if isinstance(widget_under_mouse, QTextEdit):
    if h_scroll_bar := widget_under_mouse.horizontalScrollBar():
    new_value = h_scroll_bar.value() - event.angleDelta().y()
    h_scroll_bar.setValue(new_value)
    return True
    return super().eventFilter(obj, event)


    The problem is that this filter is only activated when I reach the bottom or the begin of the text within the QTextEdit. I tried setting it in different locations:
    At the app = QApplication(...) definition:
    app.installEventFilter(ScrollFilter()) # ScrollFilter(QObject) beeing a class build around the filter
    or inside my MainWindow:
    self.installEventFilter(self)
    or with the actual QTextEdit:
    self.my_text_edit.installEventFilter(self)

    Every time I ran into the same problem. Maybe this is because I don't use this return anonymous reference, but I kinda need to know the root-class of the widget because I also have other Widgets which aren't allowed to be scrolled vertically.

    Continue reading...

Compartilhe esta Página