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:
- Add an ID to your ListView to easily reference its selected index.
- Use a Shortcut component to listen for the standard copy keystroke (works with Ctrl+C on Windows/Linux and Cmd+C on macOS).
- 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: listViewlets us directly access the ListView'scurrentIndexproperty, which tracks the user-selected item. - Cross-platform Shortcut: Using
StandardKey.Copyensures the shortcut works natively on all operating systems, no hardcoded key combinations needed. - Clipboard Access:
Qt.application.clipboardis a built-in QML singleton that provides access to the system clipboard. ThesetText()method adds your selected item's text to it instantly. - Error Prevention: We check if
currentIndexis 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
相关产品推荐
相关产品推荐

