How to use addItem method of SplitView ?



  • Dear All,

    I want to add an Item to a splitview on some event. I took the SplitView example from the documentation and added a MouseArea which call the addItem method with a Rectangle item. The problem is that I get an error message like:
    split.qml:71 Expected token `)' which correspond to the line splitview.addItem( Rectangle { Text { text: "new" } } )
    I don't understand what happens. Here is my code:

    import QtQuick 2.5
    import QtQuick.Controls 1.4
    import QtQuick.Layouts 1.1
    
    SplitView {
    
        id: splitview
    
        width: 800
        height: 800
        orientation: Qt.Horizontal
    
        Rectangle {
            width: 200
            Layout.maximumWidth: 400
            color: "lightblue"
            Text {
                text: "View 1"
                anchors.centerIn: parent
            }
        }
        Rectangle {
            id: centerItem
            Layout.minimumWidth: 50
            Layout.fillWidth: true
            color: "lightgray"
            Text {
                text: "View 2"
                anchors.centerIn: parent
            }
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    splitview.addItem( Rectangle { Text { text: "new" } } )
                }
            }
        }
        Rectangle {
            width: 200
            color: "lightgreen"
            Text {
                text: "View 3"
                anchors.centerIn: parent
            }
        }
    }

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    From what I've gathered, it should be something like

    Component {
       id: itemToAdd
       Rectangle {
           Text {
                text: "new"
           }
       }
    }
    
    Rectangle {
            id: centerItem
    //your code
        onClicked: {
            var newItem = itemToAdd.createObject()
            splitView.addItem(newItem)
        }
    }
    

    Hope it helps



  • Thanks, it helps indeed.
    You gave a solution, now for the explanation, if I understand correctly it’s you have to use the createObject method when you are in a javascritpt part.


  • Lifetime Qt Champion

    It's not because of the javascript part. createObject is used to create new objects dynamically the way you want it. What you where doing is declaring a Rectangle not instantiating a new one when calling addItem.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.