从 Qt Quick 的文件夹中读取 n 个随机文件
我正在编写我的第一个 Qt Quick 应用程序,但在其他环境中做一些简单的事情时遇到了很多麻烦。我想显示文件夹中的 n 个随机图像。为此,我使用了FolderListModel,但问题是我没有看到任何直接访问文件列表的方法。所以这是我的黑客方法:
- 使用FolderListModel读取文件
- 使用文本组件作为
- 文本组件的onTextChanged委托获取文件名(这部分有效)并将其添加到某个ListModel中
- 随机化ListModel,然后用它来显示文件
我有很多问题和疑问,但首先,执行此操作的明智方法是什么(请这样做,以便列表部分不必用 C++ 编写)?
现在有 2 个问题 - 我不知道如何从 Text 组件访问 ListModel;我不知道如何使 ListModel 公开/可从另一个显示图像的组件访问。
下面是代码:
import QtQuick 1.0
import Qt.labs.folderlistmodel 1.0
ListView {
width: 200; height: 300
FolderListModel {
folder: "file:///C:/somefolder"
id: folderModel
nameFilters: ["*.jpg"]
}
Component {
id: fileDelegate
Text { id: intext
text: fileName
//the next line fails, Can't find variable: anotherModel
onTextChanged: anotherModel.append([{name: intext.text}]
)
}
}
model: folderModel
delegate: fileDelegate
ListModel {
id: anotherModel
}
}
I'm writing my first Qt Quick application and I'm having lots of trouble doing things that are simple in other environments. I want to display n random images from a folder. For this purpose I'm using FolderListModel, but the trouble is that I don't see any methods to access list of files directly. So here's my hackish approach:
- Use FolderListModel to read files
- Use Text component as delegate
- onTextChanged of Text component gets the filename (this part works) and adds it to some ListModel
- randomize the ListModel and then use it to display files
I have many problems and questions, but first of all, what is the sane way to do this (please make it so that the list part doesn't have to be written in c++)?
There are 2 problems for now - I can't figure out how to access the ListModel from Text component; and I can' t figure out how to make the ListModel public/accessible from another component that will display the images.
Below is the code:
import QtQuick 1.0
import Qt.labs.folderlistmodel 1.0
ListView {
width: 200; height: 300
FolderListModel {
folder: "file:///C:/somefolder"
id: folderModel
nameFilters: ["*.jpg"]
}
Component {
id: fileDelegate
Text { id: intext
text: fileName
//the next line fails, Can't find variable: anotherModel
onTextChanged: anotherModel.append([{name: intext.text}]
)
}
}
model: folderModel
delegate: fileDelegate
ListModel {
id: anotherModel
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的代码几乎适合我。我收到错误“QML ListModel:附加:值不是对象”。这是因为您追加了数组。
如果您删除行中的括号,
它就可以工作。要使 anotherModel 成为公共属性,请将其写为
Your code almost works for me. I get the error "QML ListModel: append: value is not an object". This is because you append arrays.
If you remove the brackets in line
it works. To make anotherModel a public property write it as