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

如何缩短Qt Quick中ItemDelegate的onPressAndHold事件触发时长

Qt Quick 缩短ItemDelegate长按触发时长的实现方案

方法一:自定义长按逻辑(仅当前列表生效,推荐)

你可以在ItemDelegate内部嵌套一个自定义MouseArea,手动设置pressAndHoldInterval属性自定义触发间隔,完全不影响应用内其他组件的长按行为,修改后的完整代码如下:

import QtQuick 2.12
import QtQuick.Controls 2.15
import QtQuick.Window 2.12

Window {
    width: 640
    height: 480
    visible: true

    ListView {
        id: list
        anchors.fill: parent

        model: ListModel {
            id: listView
            ListElement { name: "Element 1" }
            ListElement { name: "Element 2" }
            ListElement { name: "Element 3" }
            ListElement { name: "Element 4" }
        }

        delegate: ItemDelegate {
            property string textcolor: "black";
            contentItem: Text {
                id: content
                width: parent.width
                text: name
                color: textcolor
            }

            // 新增自定义MouseArea处理长按
            MouseArea {
                anchors.fill: parent
                pressAndHoldInterval: 300 // 自定义长按间隔,单位毫秒,按需调整
                onPressAndHold: {
                    textcolor = "red"
                }
                // 兼容原有点击事件透传,保留ItemDelegate的默认点击效果
                propagateComposedEvents: true
                onClicked: mouse.accepted = false
            }
        }
    }
}

注:如果不需要保留ItemDelegate原有的点击、选中交互效果,可以删除propagateComposedEvents和onClicked两行配置。


方法二:全局修改长按间隔(全应用生效)

如果需要调整整个应用所有组件的长按触发间隔,可以在C++入口main.cpp中修改全局配置,代码如下:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QStyleHints>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    // 全局设置长按间隔,单位毫秒
    app.styleHints()->setMousePressAndHoldInterval(300);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 17:45:08