CodeTower
CodeTower

Reputation: 6333

Reference to objects id in QML

I'm trying to define a generic button in QML for use in other components. It should call a onCLick method on a object and pass its id to the function. Everything works except for the id part.

The button is defined with the following code:

Rectangle {
    width: 100
    height: 20
    color: "#d1d7f5"
    radius: 10
    property string btnText

    MouseArea {
        anchors.fill: parent
        onPressed: parent.color = "#645fa9"
        onReleased: parent.color = "#d1d7f5"
        onClicked: {
            context.onClicked(this.id) /// This is the line of problem
        }
    }
    border.color: "#645fa9"
    border.width: 2

    Text {
        id: textBtn
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter
        color: "#2e3b7f"
        text: parent.btnText
        font.bold: true
        font.family: "Verdana"
        font.pixelSize: 30
    }

}

The button can the be used in another QML file as this:

Button {
    id: button1
    x: 141
    y: 30
    btnText: "A Button"

}

The Python I use to receive the signal is here:

class Context(QObject):

    @Slot(object)
    def onClicked(self, btn):
        print btn

When the button is clicked it prints None. If this.id is replaced with a string it prints the string. I also tried to give the Rectangle an id property, but it didn't work.

Upvotes: 1

Views: 963

Answers (1)

sam
sam

Reputation: 2820

I think there is no way to get its id field. You might add an extra property or use your btnText for the purpose of distinguishing buttons.

Upvotes: 1

Related Questions