Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML inheritance

Suppose I have a few items with same behavior:

onActiveFocusChanged: {
    this.state = activeFocus ? "shown" : "hidden"
}

states: [
    State {
        name: "shown"
        PropertyChanges {
            target: myServersLV
            height: 27 * 3
            opacity: 1
        }
    },

    State {
        name: "hidden"
        PropertyChanges {
            target: myServersLV
            height: 0
            opacity: 0
        }
    }
]


Behavior on opacity {
    NumberAnimation { duration: 250
        easing {
            type: Easing.OutElastic
            amplitude: 0.5
            period: 2.5
        }
    }
}

Behavior on height {
    NumberAnimation { duration: 250
        easing {
            type: Easing.OutElastic
            amplitude: 0.5
            period: 2.5
        }
    }
}

In these few items the only thing that changes is target of states and animations. Is it possible to move it in one parent(super) item as like a base class in C++ and inherit this slots, behaviors, etc in QML?

like image 302
Victor Polevoy Avatar asked Oct 20 '25 11:10

Victor Polevoy


1 Answers

Yes, absolutely. The Qt docs include an example of how to create a reusable Button component. Copying from the docs, here's their Button:

 //contents of Button.qml
 import QtQuick 1.0

 Rectangle {
     id: button
     width: 145; height: 60
     color: "blue"
     smooth: true; radius: 9
     property alias text: label.text
     border {color: "#B9C5D0"; width: 1}

     gradient: Gradient {
         GradientStop {color: "#CFF7FF"; position: 0.0}
         GradientStop {color: "#99C0E5"; position: 0.57}
         GradientStop {color: "#719FCB"; position: 0.9}
     }

     Text {
         id: label
         anchors.centerIn: parent
         text: "Click Me!"
         font.pointSize: 12
         color: "blue"
     }

     MouseArea {
         anchors.fill: parent
         onClicked: console.log(text + " clicked")
     }
 }

To use this from another file, you reference it based on the filename without the .qml suffix. So a minimal example would be:

Button {}

But you want to set the text, right? All you need to do is this:

Button {
    text: "My button text"
}

Why? Because they included an alias property that lets you directly modify the variable of a sub component:

property alias text: label.text
like image 94
MrEricSir Avatar answered Oct 23 '25 08:10

MrEricSir