【问题标题】:QML ListView: how to copy selected item to clipboard?QML ListView:如何将所选项目复制到剪贴板?
【发布时间】:2020-01-22 12:57:56
【问题描述】:

我有带有文本项的 ListView:

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 300
    height: 300

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

    ListView {
        anchors.fill: parent

        model: listModel
        delegate: Text {
            text: model.name
            width: ListView.view.width

            MouseArea {
                anchors.fill: parent
                onClicked: parent.ListView.view.currentIndex = model.index
            }
        }

        highlight: Rectangle {
            color: 'light grey'
        }
    }
}

用户可以通过鼠标点击在这个列表中选择一个项目。我想通过 Ctrl+C 将所选项目文本复制到剪贴板。

这个任务有简单的解决方案吗?是否可以在没有 C++ 代码的情况下仅在 QML 中执行此操作?

【问题讨论】:

    标签: qt qml qt5 qtquick2


    【解决方案1】:

    一般来说,您应该使用QClipBoard,因为此问题的答案表明,因为无法从 QML 访问 QClipBoard 对象,但解决方法是使用不可见的 TextEdit,因为该对象可以将文本保存在剪贴板:

    import QtQuick 2.12
    import QtQuick.Window 2.12
    
    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
            anchors.fill: parent
            model: listModel
            delegate: Text {
                text: model.name
                width: ListView.view.width
    
                MouseArea {
                    anchors.fill: parent
                    onClicked: parent.ListView.view.currentIndex = model.index
                }
            }
            highlight: Rectangle {
                color: 'light grey'
            }
        }
        TextEdit{
            id: textEdit
            visible: false
        }
        Shortcut {
            sequence: StandardKey.Copy
            onActivated: {
                textEdit.text = listModel.get(listView.currentIndex).name
                textEdit.selectAll()
                textEdit.copy()
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 2010-12-09
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多