在QML中引用对象id

时间:2014-03-13 14:30:11

标签: python qt qml

我试图在QML中定义一个通用按钮,以便在其他组件中使用。它应该在对象上调用onCLick方法并将其id传递给该函数。一切都有效,除了id部分。

使用以下代码定义按钮:

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
    }

}

该按钮可以在另一个QML文件中使用,如下所示:

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

}

我用来接收信号的Python在这里:

class Context(QObject):

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

单击该按钮时,将打印None。如果用字符串替换this.id,则会打印字符串。 我还试图给Rectangle id一个属性,但它没有用。

1 个答案:

答案 0 :(得分:1)

我认为没有办法获得它的id字段。 您可以添加额外的属性或使用btnText来区分按钮。