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

QML ListView如何实现选中项通过Ctrl+C复制到剪贴板?

Answer

Absolutely! You can implement this entirely in QML without any C++ code. Here's a clean, cross-platform solution:

Key Changes Needed:

  1. Add an ID to your ListView to easily reference its selected index.
  2. Use a Shortcut component to listen for the standard copy keystroke (works with Ctrl+C on Windows/Linux and Cmd+C on macOS).
  3. Access the system clipboard via QML's built-in clipboard singleton to set the copied text.

Modified Full Code:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12 // Required for cross-platform standard shortcuts

Window {
    visible: true
    width: 300
    height: 300

    ListModel {
        id: listModel
        ListElement { name: "Bill Smith" }
        ListElement { name: "John Brown" }
        ListElement { name: "Sam Wise" }
    }

    ListView {
        id: listView // Added ID to reference the ListView directly
        anchors.fill: parent
        model: listModel
        delegate: Text {
            text: model.name
            width: ListView.view.width
            MouseArea {
                anchors.fill: parent
                onClicked: listView.currentIndex = model.index // Cleaner reference using the ListView ID
            }
        }
        highlight: Rectangle { color: 'light grey' }
    }

    Shortcut {
        sequence: StandardKey.Copy // Cross-platform copy shortcut
        onActivated: {
            // Only copy if an item is actually selected
            if (listView.currentIndex !== -1) {
                const selectedName = listModel.get(listView.currentIndex).name;
                Qt.application.clipboard.setText(selectedName);
            }
        }
    }
}

Explanation:

  • ListView ID: The id: listView lets us directly access the ListView's currentIndex property, which tracks the user-selected item.
  • Cross-platform Shortcut: Using StandardKey.Copy ensures the shortcut works natively on all operating systems, no hardcoded key combinations needed.
  • Clipboard Access: Qt.application.clipboard is a built-in QML singleton that provides access to the system clipboard. The setText() method adds your selected item's text to it instantly.
  • Error Prevention: We check if currentIndex is not -1 (meaning no item is selected) before attempting to copy, avoiding unnecessary errors.

This solution is lightweight, maintainable, and requires no additional C++ code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:22:40