Reputation: 108
I have this minimal application that mimics my real one. I have a main qml window with a listview list model and delegate in the same file:
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component{
id:deleg
CheckBox{
id:chk1
contentItem: Text {
id: txt
anchors.left : parent.indicator.right
anchors.leftMargin: 10
anchors.verticalCenter: parent.verticalCenter
text: dataname
color: "blue"
}}}
ListModel {
id: mod
ListElement{
dataname :'here'
}
ListElement{
dataname : 'there'
}
}
ListView{
id: view
width: 200
height:100
anchors.left: parent.left
anchors.top: parent.top
model: mod
delegate: deleg//CheckDelegate {}
} }
main.cpp only load that qml file, like a standard empty Qt Quick application created by Qtcreator.
This will display 2 checkboxes with blue text, all right. Now, If I put the delegate's code in a new qml file, called ChkDelegate, and I replace list view delegate with call to ChkDelegate (like in comment above), I face 1 issue, no text is displayed, which I understand, because dataname is not resolved. I have tried using link in the brackets, like
CheckDelegate { txt : dataname }
but I can't reach txt property, and Component does not allow to put extra property alias in them. How can I solve that? Thanks,
Upvotes: 0
Views: 2429
Reputation: 49329
CheckBox
already has a text
property so you can make the binding from the scope that has visibility:
delegate: CheckDelegate { text: dataname }
And in your Text
element, you can bind to that:
text: chk1.text
Also, it is a very bad idea to name your components the same as stock QML components, because that constitutes a naming collision. You'd have to import
stock QML modules as Identifier
in order to resolve it, which is not ideal. And stock QML components seem to take precedence to user defined ones, but even if they didn't, it would still not be ideal. So when you instantiate CheckDelegate
you are not creating the one you defined, but the one Qt defines.
Upvotes: 1
Reputation: 244301
First of all I will not use CheckDelegate since it is Default Item, I will change the name to MyCheckDelegate. Going to the problem considers that MyCheckDelegate is a component so it must be generic, besides that when it is overwritten you must encapsulate so you should not use dataname but the same control since the id has a scope, in general you should create a property that gets the information outside and update the internal elements but in this case we will take advantage of the text property of the CheckBox:
MyCheckDelegate.qml
import QtQuick 2.0
import QtQuick.Controls 2.4
CheckBox{
id:control
contentItem: Text {
id: txt
anchors.left : parent.indicator.right
anchors.leftMargin: 10
anchors.verticalCenter: parent.verticalCenter
color: "blue"
text: control.text
}
}
*.qml
// ...
delegate: MyCheckDelegate{
text: dataname
}
// ...
Upvotes: 1