问题描述
我创建了一个 ListView,它显示了用户定义的几页内容(纯文本).显示的页面是一个委托.一次只能看到一页.我决定用它来捕捉一个项目,就像 iOS 启动器的工作方式一样.用户只需在页面之间滑动即可.(这是在触摸屏上使用的)
I created a ListView, which displays a couple of pages of content defined by the user (plain text). The page displayed is a delegate. Only one page is visible at a time. I decided to use it to get snapping to one item, in the same way the iOS' launcher works. The user simply flicks between the pages. (this is to be used on touch screens)
我需要有当前显示页面的索引才能进行某些操作.ListView 的 currentIndex 始终保持 == 0.我怎样才能得到它?
I need to have the index of the currently displayed page for some operation. currentIndex of the ListView always stays == 0. How can I get it?
对于喜欢代码的人:
ListView
{
onCurrentIndexChanged: console.log(currentIndex) // this gets called only once - at startup
delegate: Column
{
// The page displayed, only one page at a time
}
}
谢谢
推荐答案
有很多方法可以获取屏幕中显示的当前项目的索引.如果可以获取当前页面的xy坐标,可以使用indexAt 方法.
There are many ways to get the index of current item that is displayed in the screen. If you can get the x-y coordinate of current page, you can use indexAt method in ListView.
并且在每个委托中,您可以使用委托范围内的index
角色找到索引.index
就像您在模型中声明的角色,由 ListView 自动分配.例如,
And in each delegate, you can find the index using index
role within the scope of the delegate. The index
is like a role you declared in your model, and is automatically assigned by ListView. For example,
ListView
{
delegate: Column
{
property int indexOfThisDelegate: index
//...
}
}
index
角色介绍这里:
代表也可以使用包含模型中项目索引的特殊索引角色.请注意,如果从模型中删除项目,则此索引设置为 -1...
另一种方法是显式地为 ListView 中的 currentItem
属性赋值,这样视图可以自行滚动.这是 Qt 中的一个简单 示例文档,类似于您的应用程序.
Another way is to explicitly assign value to the currentItem
property in ListView, so the view can scroll by itself. Here is an simple example in Qt documentation, which is similar to your application.
这篇关于获取当前显示的委托的索引 - QML ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!