将由QAbstractListModel派生的类提供的QIcon绑定到QML Image

时间:2014-02-18 10:26:38

标签: c++ qt qml qt-quick qabstractitemmodel

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

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

                Image {
                    source: model.DecorationRole
                }

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

但是这导致了这个错误:

  

无法将QIcon分配给QUrl

如何正确地做到这一点?

2 个答案:

答案 0 :(得分:2)

您无法指定QIcon作为QML Image的来源。

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

images://myicons/<icon_id>

此字符串是您设置为Image.source的网址。

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

  • 创建QQuickImageProvider的子类,例如MyIconProvider
  • 覆盖将requestPixmap作为参数并返回像素数据的函数id

然后在main.cpp

中注册图片提供者
MyIconProvider *mip = new MyIconProvider();
engine.addImageProvider("myicons", mip); 

答案 1 :(得分: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;
};

<强> ImageProvider.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
    //...
}