QML: Multi-level Menu from ListModel - qt

I have an example multi-level ListModel:
ListModel{
id: myModel
ListElement{
name: "File"
subItems:[
ListElement{
name: "Open"
},
ListElement{
name: "Open Recent"
subItems:[
ListElement{
name: "Bla.txt"
}
]
},
ListElement{
name: "Save"
},
ListElement{
name: "Save as"
},
ListElement{
name: "Exit"
}
]
}
ListElement{
name: "Edit"
subItems:[
ListElement{
name: "Undo"
},
ListElement{
name: "Redo"
},
ListElement{
name: "Select All"
}
]
}
ListElement{
name: "Help"
subItems:[
ListElement{
name: "About"
}
]
}
}
Which I want to display as Menu. From here I know how to iterate model inside of Menu component. But because I have multi-level structure I should check either second level is Menu or MenuItem. Therefore I use Loader and choose which component to load(check if subItems of the element is undefined):
MenuBar{
id: menuBar
Instantiator{
id: menuBarRepeater
model: myModel
onObjectRemoved: menuBar.removeItem( object )
delegate: Loader{
sourceComponent: myModel.get(index)["subItems"]? subMenuLoader : menuItemLoader
onLoaded: {
item.name = model.name;
if(myModel.get(index)["subItems"]){
item.parentIndex = index;
item.model = model
menuBar.insertMenu( index, item )
}else{
menuBar.insertItem( index, item )
}
}
}
}
}
Finally I need to add one more Instantiator for third level of menu. I could do it recursively, but for example purpose I'll assume that I have max. 3 levels. So the components that will be loaded in code above are:
Component{
id: menuItemLoader
MenuItem{
property var name
text: name
}
}
Component{
id: subMenuLoader
Menu{
id: subMenu
property var name
property var parentIndex: index
property var model
title: name
Instantiator{
model: model
onObjectRemoved: menuBar.removeItem( object )
delegate: Loader{
sourceComponent: myModel.get(parentIndex)["subItems"].get(index)["subItems"] ? subMenuLoader : menuItemLoader
onLoaded: {
item.name = model.name;
if(myModel.get(parentIndex)["subItems"].get(index)["subItems"]){
subMenu.insertMenu( index, item )
}else{
subMenu.insertItem( index, item )
}
}
}
}
}
}
My problem is that the model that will be passed to the second level is QQmlDMListAccessorData and is not iterable. Is there any way to get children of the Intantiator model item?

So, the workaround I have found is: instead of passing the model (which has type QQmlDMListAccessorData) to subMenu, as a second-level Instantiator model I used myModel.get(parentIndex)["subItems"].get(index), which addresses to ListElement, which for QML has type QQmlListModel(%index%) and can be used exactly as its parent (myModel itself)

Related

How to create different component base on ListModel in QML

There are 9 parameters that I need to use TextField1 to input value.
So I use
ListModel lstPara {
ListElement{
text:"A";value:"123"
}...(9 Elements)
}
Grid{
id: grid
anchors.fill: parent
columns: 3
spacing: 5
Repeater {
id: rpPara
model: lstPara
delegate: TextField1 {
}
}
}
But now there is a parameter that i need to use in another QML type to set the value, all others are used in TextField1.
I tried to define ListModel like this
ListModel lstPara{
ListElement {
text: "A";
type: 1";
value: "123"
}
ListElement {
text: "B";
type: 2";
value: "321"
}
...(9 Elements)
}
Grid{
id: grid
anchors.fill: parent
columns: 3
spacing: 5
Repeater {
id: rpPara
model: lstPara
(some code : like this)
delegate: {
return type === 1 ?
TextField1 {
}
:
another QML type {
}
}
}
}
The code above can not run.
And I don`t want to write 8 TextField1 and 1 another QML type.
So, is there a way to use ListModel?
You can't directly use an Item declaration in a conditional expression like that, but you can do it with a Component. Here's an example of how to do it using a Loader as your delegate, and choosing which Component to load based on the model:
ListModel {
id: lstPara
ListElement {
text: "A"
type: 1
value: "123"
}
ListElement {
text: "B"
type: 2
value: "321"
}
}
Grid {
id:grid
anchors.fill: parent
columns: 3
spacing: 5
Repeater {
id: rpPara
model: lstPara
delegate: Loader {
sourceComponent: type === 1 ? someText : otherText
onLoaded: {
item.text = text
item.value = value
}
}
}
Component {
id: someText
Text {
property string value
color: "blue"
}
}
Component {
id: otherText
Text {
property string value
color: "red"
}
}
}

ListView with section, Remove Animation not working for the top item

I'm using a QML ListView with section, click on item to remove with animation. Here the code:
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
visible: true
width: 400
height: 400
ListView {
id: list
anchors.fill: parent
clip: true
spacing: 0
onContentYChanged: console.log("onContentYChanged: " + contentY)
onContentHeightChanged: console.log("onContentHeightChanged: " + contentHeight)
model: ListModel {
id: myModel
ListElement {name: "Item 1";type: "A"}
ListElement {name: "Item 2";type: "A"}
ListElement {name: "Item 3";type: "B"}
}
delegate: Rectangle {
width: parent.width
height: 50
color: (index % 2 == 1) ? "#5678a2" : "#88a345"
Text {
anchors.verticalCenter: parent.verticalCenter
text: name
}
MouseArea {
anchors.fill: parent
onClicked: {
console.log("remove: " + index + ", contentY:" + list.contentY)
myModel.remove(index)
}
}
}
section.property: "type"
section.delegate: Rectangle {
height: 30
Text {
anchors.verticalCenter: parent.verticalCenter
text: section
}
}
displaced: Transition {
NumberAnimation { properties: "x,y"; duration: 500; easing.type: Easing.OutCubic }
}
remove: Transition {
NumberAnimation { property: "opacity"; from: 1.0; to: 0; duration: 500 }
NumberAnimation { property: "scale"; from: 1.0; to: 0; duration: 500 }
}
}
}
When I clicked on the first item(Item 1), it got deleted, but the Item 2 was flying up to outside the window. The ListView displayed the remaining items in wrong positions. ContentY changed to 80 (which was the y position of Item 2 before) instead of remaining at 0.
qml: onContentHeightChanged: 300
qml: onContentHeightChanged: 240
qml: onContentHeightChanged: 210
qml: remove: 0, contentY:0
qml: onContentYChanged: 80
qml: onContentHeightChanged: 160
It will work correctly if:
Delete other items except the top one.
Disable either the section or animation.
I tried your code with Qt 5.13.1. And currently downloading Qt 5.15. For now it looks like it is a bug with section, because I found a lot of not not closed bug reports on bugtracker. I can suggest 2 ways of solving your problem.
Performing animation while locking removal.
Using model with categories.
1st solution I tested by meself. Here is what you need to change to try it:
Delete ListView's removal animations. Add following code to your delegate
ListView.onRemove: SequentialAnimation {
PropertyAction { target: wrapper; property: "ListView.delayRemove"; value: true }
ParallelAnimation {
NumberAnimation { target: wrapper; property: "opacity"; to: 0; duration: 500 }
NumberAnimation { target: wrapper; property: "scale"; to: 0; duration: 500 }
}
PropertyAction { target: wrapper; property: "ListView.delayRemove"; value: false }
}
What is this? ListView has a signal remove() which is called BEFORE removing an item from the view. It is described in documentation It is also noted, that
If a remove transition has been specified, it is applied after this signal is handled, providing that delayRemove is false.
So in delegate you simply block removal from view, do you animation and unblock it. I suppose it won't be as clean and beautiful as you want it to be simply because view doesn't andjust it's size in this case.
2nd solution
I didn't try to implement it, but I can imagine having a model like this:
ListModel {
id: myModel
ListElement { type: "category"; name: "cat1" }
ListElement { name: "delegate1"; type: "delegate"; catrgory: "cat1"}
ListElement { name: "delegate2"; type: "delegate"; catrgory: "cat1"}
ListElement { name: "delegate3"; type: "delegate"; catrgory: "cat1"}
ListElement { type: "category"; name: "cat2" }
ListElement { name: "delegate4"; type: "delegate"; catrgory: "cat2"}
To use this as you want, you will need to castomize your delegate accordingly and removal function accordingly, which will lead to much more complex code in comparison to what it would be if section would work properly.
UPD: Same problem in 5.15

In 'AppListView' are empty places where Loader should load Component with 'SimpleRow'

I have a code application written in QT/QML and V-PLAY on the github here:
My problem:
I want to use AppListView to display different elements (like Button or SwitchApp) in 'Ustawienia' (Settings) page dependent on elements in array:
property var typeOfElementsInSettings: ['switch','switch','button','switch']
I use 'delegete: Loader' to do It, I inspired in this thread. I load component from other file, one will have Button inside, other AppSwitcher. Loader inserts SimpleRow to AppListView, I know It because variable myIndex should increment when SimpleRow is added and It was incremented but I can't see anything. I mean that I see empty space in place where should be displayed SimpleRow.
See screenshot:
Android Theme:
iOS Theme:
This is my code in Main.qml
NavigationItem{
title: "Ustawienia"
icon: IconType.cogs
NavigationStack{
Page{
title: "Ustawienia"
AppButton{
id: przy
text: "abba"
}
AppListView{
anchors.top: przy.bottom
model: ListModel{
ListElement{
type: "kategoria 1"; name: "opcja 1"
}
ListElement{
type: "kategoria 1"; name: "opcja 2"
}
ListElement{
type: "kategoria 2"; name: "opcja 3"
}
ListElement{
type: "Opcje programisty"; name: "Czyszczenie ustawień aplikacji"
}
}
section.property: "type";
section.delegate: SimpleSection {
title: section
}
delegate: Loader{
sourceComponent: {
switch(typeOfElementsInSettings[myIndex]){
case "switch":
console.log(typeOfElementsInSettings[myIndex])
console.log("s")
return imageDel;
case "button":
console.log(typeOfElementsInSettings[myIndex])
console.log("b")
return imageDel;
}
}
}
SimpleRowSwitch { id: imageDel }
VideoDelegate { id: videoDel }
}
}
}
onSelected: {
//console.log("selected")
}
Component.onCompleted: {
//console.log("Zrobiono")
}
}
This my code in SimpleRowSwitch.qml:
import VPlayApps 1.0
import QtQuick 2.9
Component{
SimpleRow {
x: 100
y: 200
text: name;
AppSwitch{
property int indexOfElementInSettings: 0
anchors.verticalCenter: parent.verticalCenter
anchors.right: parent.right
anchors.rightMargin: dp(10)
Component.onCompleted: {
indexOfElementInSettings=myIndex
console.log(myIndex)
if(switchsSettingsLogicArray[myIndex]===1){
checked=true
} else {
checked=false
}
//myIndex++;
}
onToggled: {
console.log(indexOfElementInSettings)
}
}
Component.onCompleted: {
console.log(x)
console.log(y)
console.log(typeOfElementsInSettings[myIndex])
console.log(myIndex)
myIndex++
}
onSelected: {
console.log("abba")
}
}
}

QML Tableview display value from selected row

I have a tableview and I want to open a dialog box on onPressAndHold on a row and display the value of the cell of the row "orderNumber".
But i get the Error message: ReferenceError: row is not defined
TableView {
id: tableviewopenorders
height: 180
clip: false
visible: true
onPressAndHold: oocanceldialog.open()
TableViewColumn {
id: orderNumberColumn
role: "orderNumber"
title: "Order Number"
}
model: openordersModel
}
ListModel {
id: openordersModel
ListElement {
orderNumber: "1223455"
}
ListElement {
orderNumber: "111111"
}
}
Dialog {
id: oocanceldialog
title: "Cancel confirmation"
standardButtons: Dialog.Ok | Dialog.Cancel
x: (parent.width - width) / 2
y: (parent.height - height) / 2
Label {
text: openordersModel.get(row).orderNumber
}
onAccepted: console.log("Ok clicked")
onRejected: oocanceldialog.close()
}
row exists in the context of onPressAndHold, so it does not exist outside of it, to get the row we must use the currentRow attribute of the TableView:
currentRow : int
The current row index of the view. The default value is -1 to indicate that no row is selected.
In your case:
Label {
text: openordersModel.get(tableviewopenorders.currentRow).orderNumber
}

How do I correctly handle mouse events in a QML TableView with overlapping mouse areas?

I've got a delegate attached to my TableViewColumn that contains a MouseArea. I use the MouseArea to detect double clicks on individual cells in the table, which allows me to show a TextField for editing purposes.
The problem is the delegate MouseArea blocks mouse events from propagating through to TableView. This means that the selection behaviour of TableView no longer works. Specifically, I have SelectionMode.ExtendedSelection enabled.
The MouseArea child item is simple and originally looked like this:
MouseArea{
id: mousearea
anchors.fill: parent
onDoubleClicked: {
showTextField()
}
}
After consulting the documentation, it looked like this should work:
MouseArea{
id: mousearea
anchors.fill: parent
propagateComposedEvents: true // new
onDoubleClicked: {
showTextField()
}
onPressed: mouse.accepted = false // new
}
Which it does, except now I cannot pick up double click events anymore (in MouseArea)! Which makes sense, as it states later in the documentation:
pressed(MouseEvent mouse)
When handling this signal, use the accepted property of the mouse parameter to control whether this MouseArea handles the press and all future mouse events until release. The default is to accept the event and not allow other MouseAreas beneath this one to handle the event. If accepted is set to false, no further events will be sent to this MouseArea until the button is next pressed.
There does not seem to be a way to capture mouse events for individual cells at the TableView level. It's my first day playing around with QML, so I might have missed something obvious here, but what are my options? Note I'm using PyQt.
If it is only the the selection you want to achive you can set the selection manually:
TableView {
id: tv
itemDelegate: Item {
Text {
anchors.centerIn: parent
color: styleData.textColor
elide: styleData.elideMode
text: styleData.value
}
MouseArea {
id: ma
anchors.fill: parent
onPressed: {
tv.currentRow = styleData.row
tv.selection.select(styleData.row) // <-- select here.
}
onClicked: {
console.log(styleData.value)
}
}
}
TableViewColumn {
role: 'c1'
title: 'hey'
width: 100
}
TableViewColumn {
role: 'c2'
title: 'tschau'
width: 100
}
model: lm
}
Right now I only select. But you can write your very own selection/deselection-logic.
You might also map from the TableView.__mouseArea to the delegate.
import QtQuick 2.7
import QtQuick.Controls 1.4
ApplicationWindow {
id: appWindow
width: 1024
height: 800
visible: true
ListModel {
id: lm
ListElement { c1: 'hallo1'; c2: 'bye' }
ListElement { c1: 'hallo2'; c2: 'bye' }
ListElement { c1: 'hallo3'; c2: 'bye' }
ListElement { c1: 'hallo4'; c2: 'bye' }
ListElement { c1: 'hallo5'; c2: 'bye' }
ListElement { c1: 'hallo6'; c2: 'bye' }
ListElement { c1: 'hallo7'; c2: 'bye' }
ListElement { c1: 'hallo8'; c2: 'bye' }
ListElement { c1: 'hallo9'; c2: 'bye' }
}
TableView {
id: tv
itemDelegate: Item {
id: mydelegate
signal doubleclicked()
onDoubleclicked: console.log(styleData.value)
Text {
anchors.centerIn: parent
color: styleData.textColor
elide: styleData.elideMode
text: styleData.value
}
Connections {
target: tv.__mouseArea
onDoubleClicked: {
// Map to the clickposition to the delegate
var pos = mydelegate.mapFromItem(tv.__mouseArea, mouse.x, mouse.y)
// Check whether the click was within the delegate
if (mydelegate.contains(pos)) mydelegate.doubleclicked()
}
}
}
TableViewColumn {
role: 'c1'
title: 'hey'
width: 100
}
TableViewColumn {
role: 'c2'
title: 'tschau'
width: 100
}
model: lm
}
}

Resources