You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy应用长按屏幕后ScrollView滚动失效问题求助

解决Kivy ScrollView长按后滚动失效问题

问题根源

Kivy原生ScrollView的触摸逻辑中,长按(超过1秒)会触发内部触摸状态切换,导致后续的触摸移动事件不再被识别为滚动操作,最终出现滚动失效的情况。

解决方案

自定义ScrollView类,重写触摸事件处理逻辑,强制让所有触摸移动事件都触发滚动操作,忽略长按状态的影响。

代码修改示例

将原代码中的原生ScrollView替换为以下自定义类:

from kivy.uix.scrollview import ScrollView

class MyScrollView(ScrollView):
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            # 标记当前触摸归属于该ScrollView
            touch.ud['scroll_owner'] = self
            self._active_touch = touch
            return super().on_touch_down(touch)
        return super().on_touch_down(touch)

    def on_touch_move(self, touch):
        # 确保触摸移动时始终触发滚动逻辑
        if 'scroll_owner' in touch.ud and touch.ud['scroll_owner'] is self:
            if self._active_touch is touch:
                self._update_scroll(touch)
        return super().on_touch_move(touch)

    def on_touch_up(self, touch):
        # 清理触摸状态标记
        if 'scroll_owner' in touch.ud and touch.ud['scroll_owner'] is self:
            del touch.ud['scroll_owner']
            self._active_touch = None
        return super().on_touch_up(touch)

兼容子组件的优化

如果ScrollView内部包含Button等可交互组件,可修改on_touch_down方法,确保子组件正常交互的同时,空白区域长按后仍能滚动:

def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
        # 先让子组件处理触摸,未处理则接管为滚动触摸
        handled = super().on_touch_down(touch)
        if not handled:
            touch.ud['scroll_owner'] = self
            self._active_touch = touch
        return handled
    return super().on_touch_down(touch)

内容的提问来源于stack exchange,提问作者user21099627

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:20:24