我想出了这个解决方案。它有效,但非常欢迎任何建议或改进。
ImageProvider.h
class ImageProvider : public QQuickImageProvider
{
public:
explicit ImageProvider(myModel *myModel);
QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize);
signals:
public slots:
private:
myModel *m_myModel;
};
图像提供者.cpp
ImageProvider::ImageProvider(myModel *myModel) :
QQuickImageProvider(QQuickImageProvider::Pixmap),
m_myModel(myModel)
{
}
QPixmap ImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
{
QModelIndex index;
bool foundId = false;
for(int row = 0; row < m_myModel->rowCount(); row++)
{
index = m_myModel->index(row, 0);
QString name = QVariant(m_myModel->data(index, Qt::DisplayRole)).toString();
if(name == id)
{
foundId = true;
break;
}
}
if(!foundId)
return QPixmap();
QIcon icon = m_myModel->data(index, Qt::DecorationRole).value<QIcon>();
QPixmap pixmap = icon.pixmap(128,128);
return pixmap;
}
注册 imageProvider...
ImageProvider *imageProvider = new ImageProvider(myModel);
view->engine()->addImageProvider(QLatin1String("provider"), imageProvider);
main.qml
Component {
id: myDelegate
//...
Column {
anchors.verticalCenter: parent.verticalCenter
spacing: 5
Image {
source: "image://provider/" + model.DisplayRole
}
Text {
text: model.DisplayRole
//...
}