Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML ListView: how to copy selected item to clipboard?

Tags:

qt

qt5

qml

qtquick2

I have ListView with text items:

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'
        }
    }
}

User can select an item in this list by mouse click. I want to copy selected item text to clipboard by Ctrl+C.

Is there simple solution to this task? Is it possible to do this in QML only without C++ code?

like image 677
Andrey Epifantsev Avatar asked Oct 25 '25 03:10

Andrey Epifantsev


1 Answers

In general, you should use QClipBoard as the answers to this question indicate since the QClipBoard object cannot be accessed from QML, but a workaround is using an invisible TextEdit since this object can save the text in the clipboard:

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()
        }
    }
}
like image 74
eyllanesc Avatar answered Oct 26 '25 22:10

eyllanesc