PyQt5 QML currentIndexChanged 信号

PyQt5 QML currentIndexChanged signal

问题如下

我在 "main.qml" QML 文件中有这个 ListView:

ListView {
    id: websiteListView
    orientation: ListView.Vertical
    flickableDirection: Flickable.VerticalFlick
    anchors.fill: parent
    model: websiteModel
    focus: true
    highlight: Rectangle { color: "lightsteelblue";}
    highlightFollowsCurrentItem: true
    objectName: "websiteListView"

    delegate: Component {
        Item {
            property variant itemData: model.modelData
            width: parent.width
            height: 20

            Row {
                id: row1
                spacing: 10
                anchors.fill: parent

                Text {
                    text: name
                    font.bold: true
                    anchors.verticalCenter: parent.verticalCenter
                }

                MouseArea {
                    id: websiteMouseArea
                    anchors.fill: parent
                    onClicked: {
                        websiteListView.currentIndex = index
                    }
                }
            }
        }
    }
}

我也有这个Python剧本:

    self.__engine = QQmlApplicationEngine()
    self.__engine.load("main.qml")

    website_list = self.__engine.rootObjects()[0].findChild(QObject, "websiteListView")
    website_list.currentIndexChanged.connect(self.__website_event_print)

以及负责信号处理的函数:

@pyqtSlot(int, int)
def __website_event_print(self, current, previous):

    print(current)
    print(previous)

上面显示的代码只是整个应用程序的摘录,但我相信其他代码行与问题无关。

当我尝试 运行 我的应用程序时发生错误

TypeError: decorated slot has no signature compatible with currentIndexChanged()

我已经尝试了上述代码的大量变体,但似乎没有任何效果。我处理信号的方式是否正确?如果是这样,"currentIndexChanged" 的签名是什么?

不建议在 QML 之外连接 qml 项,因为您只能像代码显示的那样以 QObject 的形式获取它,而不能获得真正的对象,因为它是私有的,此外 currentIndexChanged 通知已经发生了变化,但没有参数传递给你得到的那些错误。

一个可能的解决方案是创建一个通过setContextProperty()插入QML的对象,并在发出信号时调用该函数:

.py:

class Helper(QObject):
    @pyqtSlot(int)
    def foo(self, index):
        print(index)

# ...

engine = QQmlApplicationEngine()
helper = Helper()
engine.rootContext().setContextProperty("helper", helper)
engine.load(QUrl.fromLocalFile("main.qml"))

.qml

ListView {
    onCurrentIndexChanged: helper.foo(currentIndex)
    // ...
}

下面link有一个例子