模型和视图:使用工作线程获取更多信息

演示如何在工作线程中实现 fetchMore(),同时保持响应式用户界面。

此示例展示了如何利用QAbstractItemModel::fetchMore() 将对象移动到QThread ,从而使数据获取不会阻塞用户界面。每次调用时,FetchWorker 会休眠 2 秒,以模拟缓慢的后台服务,然后再向用户界面线程发送更多数据。

基本功能

当数据在工作线程中获取时,模型会在列表末尾添加一个BusyIndicator 。一旦数据获取成功,BusyIndicator 就会被移除,新项目会被添加到列表中。ListView 使用的是典型的方式,不需要为处理慢速模型而进行调整。

责任

项目模型的更改(本例中为插入和删除行)必须在用户界面线程中进行。工作线程对象会缓慢地构建 DataBlock 结构,并发出dataFetched 信号,其有效载荷为QList 数据块;该信号通过Qt::QueuedConnection 发送到 ThreadedFetchMoreModel::dataReceived() 槽,后者会将其添加到用户界面线程的数据列表中。在向 Worker 对象发送 fetchDataBlock() 信号以启动获取过程之前,用户界面线程会在列表末尾添加一个占位符,并在向列表添加新项之前移除占位符。

在获取完所有可用数据后,工作线程对象会向模型发送noMoreToFetch 信号;此后,canFetchMore() 方法将始终返回false

示例项目 @ code.qt.io

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.