gpt4 book ai didi

qt - 如何在后台线程中为 QFileSystemModel 创建自定义图标

转载 作者:行者123 更新时间:2023-12-01 18:39:02 25 4
gpt4 key购买 nike

我正在 qt 中为一些自定义设计文件制作一个文件浏览器。我想将它们的预览加载为缩略图,因此我使用 QIconProvider 将图标返回到我的 QFileSystemModel

问题是创建 QIcon 的算法需要一些资源,因此我的应用程序在完成加载所有缩略图之前没有响应。

我想知道是否有任何方法可以将我的 QIconProvider 放入后台线程中,以便我的应用程序能够响应。

最佳答案

不幸的是,QFileIconProvider API 和模型 API 之间存在阻抗不匹配:QFileSystemModel 在情况发生变化时向 View 提供异步通知,但图标提供程序却不能当图标更改或变为已知时,异步通知模型。

您可以在文件系统模型和 View 之间安装身份代理。然后,该代理的 data 方法将异步查询图标。模型的同步图标提供程序将不再被使用且不必要。

// 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);
}
};

关于qt - 如何在后台线程中为 QFileSystemModel 创建自定义图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39144638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com