问题描述
在下面的代码片段中,我正在显示可变数量的TextEdit项目,每个项目都在Rectangle中,Rectangle是转发器的委托。当我点击“播放”按钮时,该插槽需要收集播放器名称并调用Q_INVOKABLE方法(未显示)以将数据传递到C ++后端。出于这个问题的目的,我只是试图在“播放”按钮的onClicked插槽中显示播放器名称,但不确定如何显示。我离开了 '???'我试图找出如何在每个委托实例的矩形内检索信息。
在这一点上,我愿意接受这种方法的解决方案,或者只是被告知我正在以错误的方式进行处理。我对Qt的QML方面真的很陌生。
谢谢
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
Item {
id: root
property int playerCount: playerCountSelect.currentValue
RowLayout {
id: layout
anchors.top: parent.top
anchors.topMargin: 5
spacing: 6
anchors.horizontalCenter: parent.horizontalCenter
Label {
text: "Enter number of players"
}
ComboBox {
id: playerCountSelect
model: [2,3,4]
}
}
RowLayout {
id: mainRow
anchors.centerIn: parent
anchors.horizontalCenter: parent.horizontalCenter
spacing: 6
RoundButton {
text: "Play"
width: 40
radius: 2
font.pointSize: 12
onClicked: {
for (var i =0; i < playerList.count; i++) {
console.log(playerList.itemAt(i).???)
}
}
}
Column {
spacing: 6
Repeater {
id: playerList
model: root.playerCount
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
width: 120
height: 32
TextEdit {
font.pointSize: 12
text: "Player " + (index+1) + " name"
}
}
}
}
RoundButton {
text: "Quit"
width: 40
radius: 2
font.pointSize: 12
}
}
}
解决方法
您只需要在中继器的代理中公开所需的属性即可。
helper.sh
然后,您可以通过执行以下操作在打印语句中访问该属性:
Repeater {
id: playerList
model: root.playerCount
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
width: 120
height: 32
// Expose the player name
property alias playerName: textField.text
TextEdit {
id: textField
font.pointSize: 12
text: "Player " + (index+1) + " name"
}
}
}