tac*_*ach 1 drag-and-drop qml qt5 qtquick2
假设我有一个 QML Row,其中有一些子对象(不一定是同一类型)。我希望能够随意重新排序。额外的好处是,能够为用户实现拖放行为。这是一个代码示例,其中Row包含我想重新排序的不同组件:
import QtQuick 2.5
import QtQuick.Controls 1.4
ApplicationWindow {
visible: true
width: 300
height: 300
Component {
id: rect
Rectangle {
color: "blue"
}
}
Component {
id: rectWithText
Rectangle {
property alias text: txt.text
color: "red"
Text {
id: txt
}
}
}
Row {
id: r
Component.onCompleted: {
rect.createObject(r,{"width": 60,"height":40})
rectWithText.createObject(r,{"width": 100,"height":40,text:"foo"})
rect.createObject(r,{"width": 40,"height":40})
}
}
}
Run Code Online (Sandbox Code Playgroud)
在QtWidgets中,有一些函数layout->removeWidget(widget),例如,layout->insertWidget(index,widget)等等,但在QML中似乎缺少它们。
我发现了一些使用ListView/GridView和模型/委托方法的示例,但它们通常无法处理不同的组件,因此它们作为Row.
有没有办法在 QML 中做到这一点,还是我运气不好?
小智 5
这有点黑客行为,但无论如何都有效。它不需要使用模型。
import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.1
Window {
visible: true
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
Column {
id: column
anchors.fill: parent
anchors.centerIn: parent
Button {
text: "shuffle"
onClicked: {
var array = [button1, button2, button3]
for (var a in array) { array[a].parent = null }
array = shuffle(array)
for (a in array) { array[a].parent = column }
}
}
Button {
id: button1
text: "I am button 1"
}
Button {
id: button2
text: "I am button 2 "
}
Button {
id: button3
text: "I am button 3"
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1670 次 |
| 最近记录: |