[英]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)
// ...
}
在以下链接中有一个示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.