Search code examples
compose-desktop

Compose desktop can't detect horizontal scrolling


so i'm developing a desktop application using compose desktop and I need to detect horizontal scroll.

here is what I tried already:

  .onPointerEvent(PointerEventType.Scroll) { println(it.changes.first().scrollDelta)}

the problem is i can only get vertical scrolls! how can I detect horizontal scroll event?

by the way by horizontal scroll I mean scrolling with touchpad


Solution

  • To get horizontal scroll changes use x axis in scrollDelta:

    .onPointerEvent(PointerEventType.Scroll) { 
       val scrollDelta = it.changes.fold(Offset.Zero) { acc, c -> acc + c.scrollDelta }
       println(scrollDelta.x) 
    }
    

    Note: it is needed to fold all changes, otherwise some scroll deltas can be skipped.

    Also, you can use horizontalScroll modifier to make a component horizontally scrollable automatically.

    val scrollState = remember { ScrollState(initial = 0) }
    Box(modifier = Modifier.size(100.dp).horizontalScroll(scrollState)) {
      Text("Scrollable".repeat(20))
    }
    
    LaunchedEffect(scrollState.value) {
      println(scrollState.value)
    }