QML中对象ID的引用

1 投票
1 回答
922 浏览
提问于 2025-04-17 22:08

我正在尝试在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 个回答

1

我觉得没办法获取它的id字段。你可以加一个额外的属性,或者用你的btnText来区分不同的按钮。

撰写回答