2014-02-18 41 views
1

我嘗試綁定由QAbstractListModel導出到QML圖片這樣的類提供一個QIcon提供QIcon:綁定由QAbstractListModel導出到QML圖片類

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

       Image { 
        source: model.DecorationRole 
       } 

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

但是這導致了這個錯誤:

Unable to assign QIcon to QUrl

如何正確執行此操作?

回答

2

您不能指定QIcon作爲QML Image的來源。

您需要做的是爲您的圖標選擇自定義網址格式,例如,

images://myicons/<icon_id> 

該字符串是您爲Image.source設置的URL。

現在,您創建和註冊imageprovider,它提供的圖標,當你發送從QML請求的URL:

  • 創建的QQuickImageProvider一個子類,例如MyIconProvider
  • 覆蓋,是以id作爲和參數,並返回像素數據

然後你在main.cpp

MyIconProvider *mip = new MyIconProvider(); 
engine.addImageProvider("myicons", mip); 
+0

你可否透露更多關於如何返回的像素數據(這顯然必須來自我的模型)? – avb

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