1

我尝试将由 QAbstractListModel 派生的类提供的 QIcon 绑定到 QML Image,如下所示:

Component {
    id: myDelegate
    //...
            Column {
                anchors.verticalCenter: parent.verticalCenter
                spacing: 5

                Image {
                    source: model.DecorationRole
                }

                Text {
                    text: model.DisplayRole
    //...
}

但这会导致此错误:

无法将 QIcon 分配给 QUrl

如何正确执行此操作?

4

2 回答 2

2

我想出了这个解决方案。它有效,但非常欢迎任何建议或改进。

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
    //...
}
于 2014-02-21T10:15:25.030 回答
2

您不能将 a 指定QIcon为 QML 的源Image

您需要做的是为您的图标选择自定义 URL 格式,例如

images://myicons/<icon_id>

此字符串是您设置为Image.source.

现在您创建并注册一个 imageprovider,它会在您从 QML 发送请求的 URL 时提供图标:

  • 创建 的子类QQuickImageProvider,例如MyIconProvider
  • 覆盖requestPixmap接受idas 和参数并返回像素数据的函数

然后您在您的main.cpp

MyIconProvider *mip = new MyIconProvider();
engine.addImageProvider("myicons", mip); 
于 2014-02-19T20:32:32.567 回答