PyQt5 QML currentIndexChanged信号

时间:2017-11-19 11:53:23

标签: python pyqt qml pyqt5 qt-signals

问题如下。

我在“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”的签名是什么?

1 个答案:

答案 0 :(得分:0)

不建议将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中有一个示例