2014-02-28 56 views
1

我試圖在QTreeView中顯示圖像以及其他一些數據。爲此,我創建了一個QAbstractItemModel。在data方法中,我返回列索引0和1的一些字符串,第三個我希望返回一個圖像。但是,此圖像未顯示。在QTreeView中顯示圖像

當我將圖像作爲裝飾返回時,它顯示正常,但我希望將點擊偵聽器添加到將觸發某些事件的圖像。我也希望將我的圖像放在樹視圖的最右側,這似乎需要一個自定義委託。由於這些原因,我爲圖片創建了一個單獨的列。

圖片在構造函數中創建這樣的:mEditImage = QImage(":/images/myImage.png");

爲MyModel

QVariant MyModel::data(const QModelIndex &index, int role) const { 
    if (!index.isValid()) { 
     return QVariant(); 
    } 

    if(role == Qt::FontRole) { 
     return fontData(index); 
    } 

    if(role == Qt::ForegroundRole) { 
     return foreGroundData(index); 
    } 


    MyModelItem *item = getItem(index); 

    /* 
    * Use decoration to display image. Probably needs a 
    * custom delegate to be able to position the image correctly. 
    * (http://www.qtcentre.org/threads/49639-decoration-position-and-alignment) 
    * (https://qt-project.org/forums/viewthread/24493) 
    * 
    * Will use extra column for now instead. Might help with click 
    * listeners as well. 
    * 
    * if(role == Qt::DecorationRole && item->parent() != mRootItem) { 
     return index.column() == 1 ? mEditImage : QVariant(); 
    }*/ 

    if(role == Qt::SizeHintRole) { 
     return mEditImage.size(); 
    } 

    if (role == Qt::DisplayRole) { 

     QString id = QString::number(item->id()); 
     QString name = item->name(); 

     if(item->parent() != mRootItem && index.column() == 2) { 
      return mEditImage; 
     } 

     if(item->parent() == mRootItem){ 
      return index.column() == 0 ? name : ""; 
     } else { 
      return index.column() == 0 ? id : name; 
     } 
    } else if(role == Qt::BackgroundRole) { 
     return QVariant(); 
    } 

我有一個看看這裏:

http://www.qtcentre.org/threads/29550-How-do-I-display-a-picture-on-a-QTableView-cell

How to set an image for a row?

我已經嘗試過將圖像轉換爲QPixmapQIcon,並嘗試將其嵌入到QLabel(無法轉換爲QVariant),但沒有成功。將圖像更改爲QString將顯示該字符串,以便行/列邏輯看起來很好。刪除SizeHintRole邏輯也沒有任何區別。

任何幫助理解如何在QTreeView中顯示圖像數據將是有幫助的。我似乎從錯誤的方向着手。

乾杯。

回答

3

沒關係,如何存儲圖像。 QPixmap是速度繪製的前提。有關角色

QVariant MyModel::data(const QModelIndex &index, int role) const 
{ 
item = itemFromIndex(index); // Your item implementation 
... 
case Qt::DisplayRole: 
    return item->getText(); 
case Qt::DecorationRole: 
    return item->getImage(); 
} 

閱讀Qt的文檔,這是很好的 - http://doc.qt.io/qt-4.8/qt.html#ItemDataRole-enum

+0

好的,謝謝。我以爲我可以使用DisplayRole來顯示圖像。謝謝。 – span