And*_*sev 3 qt qml qt5 qtquick2
我有带有文本项目的 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'
}
}
}
Run Code Online (Sandbox Code Playgroud)
用户可以通过单击鼠标在此列表中选择一个项目。我想通过Ctrl+将所选项目文本复制到剪贴板C。
这个任务有简单的解决方案吗?是否可以仅在 QML 中执行此操作而不使用 C++ 代码?
一般来说,您应该使用QClipBoard该问题的答案,因为QClipBoard无法从 QML 访问该对象,但解决方法是使用不可见对象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()
}
}
}
Run Code Online (Sandbox Code Playgroud)