如何在后台线程中为QFileSystemModel创建自定义图标 [英] How to create custom icons for QFileSystemModel in a background thread
问题描述
我正在qt中创建一些自定义设计文件的文件浏览器.我想将其预览作为缩略图加载,因此,我使用QIconProvider
将图标返回到我的QFileSystemModel
.
I am making a file browser in qt for some custom design-files. I want to load their preview as their thumbnail and for that reason I am using QIconProvider
to return the Icon to my QFileSystemModel
.
问题在于创建QIcon
的算法需要一些资源,因此,我的应用程序在完成加载所有缩略图之前没有响应.
The problem is that the algorithm that creates the QIcon
needs some resources and as a result my application is not responsive until it finishes loading all the thumbnails.
我想知道是否有什么方法可以将QIconProvider
放在后台线程中,以便我的应用程序能够响应.
I am wondering if there is any way to put my QIconProvider
in a background thread, so that I have my application responsive.
推荐答案
不幸的是,在QFileIconProvider
API和模型api之间存在阻抗不匹配:QFileSystemModel
在事物发生变化时向视图提供异步通知,但是图标更改或变得已知时,图标提供程序无法异步通知模型.
Unfortunately, there's an impedance mismatch between the QFileIconProvider
API and the model api: the QFileSystemModel
provides asynchronous notifications to the view when things change, but the icon provider can't asynchronously notify the model when icons change or become known.
您可以在文件系统模型和视图之间安装身份代理.然后,该代理的data
方法将异步查询图标.然后,该模型的同步图标提供程序就不再使用且不需要了.
You can install an identity proxy between the file system model and the view(s). That proxy's data
method would then query the icons asynchronously. The model's synchronous icon provider is then unused and unnecessary.
// https://github.com/KubaO/stackoverflown/tree/master/questions/icon-proxy-39144638
#include <QtWidgets>
#include <QtConcurrent>
/// A thread-safe function that returns an icon for an item with a given path.
/// If the icon is not known, a null icon is returned.
QIcon getIcon(const QString & path);
class IconProxy : public QIdentityProxyModel {
Q_OBJECT
QMap<QString, QIcon> m_icons;
Q_SIGNAL void hasIcon(const QString&, const QIcon&, const QPersistentModelIndex& index) const;
void onIcon(const QString& path, const QIcon& icon, const QPersistentModelIndex& index) {
m_icons.insert(path, icon);
emit dataChanged(index, index, QVector<int>{QFileSystemModel::FileIconRole});
}
public:
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const override {
if (role == QFileSystemModel::FileIconRole) {
auto path = index.data(QFileSystemModel::FilePathRole).toString();
auto it = m_icons.find(path);
if (it != m_icons.end()) {
if (! it->isNull()) return *it;
return QIdentityProxyModel::data(index, role);
}
QPersistentModelIndex pIndex{index};
QtConcurrent::run([this,path,pIndex]{
emit hasIcon(path, getIcon(path), pIndex);
});
return QVariant{};
}
return QIdentityProxyModel::data(index, role);
}
IconProxy(QObject * parent = nullptr) : QIdentityProxyModel{parent} {
connect(this, &IconProxy::hasIcon, this, &IconProxy::onIcon);
}
};
这篇关于如何在后台线程中为QFileSystemModel创建自定义图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!