2014-01-25 61 views
0

此代碼將只顯示同一行中的相同圖像。如何在ImageDelegate中傳遞不同的圖像路徑?謝謝在qtableview pyqt4 python中使用委託的圖像?

class testQT4(QtGui.QTableView): 
    def __init__(self, parent=None): 
     QtGui.QTableView.__init__(self, parent) 
     self.setItemDelegateForColumn(1, ImageDelegate(parent)) 


     #table header 
     header = [ 'ID','image'] 
     tabledata = [[1,2],[3,4]] 
     #create table model 
     self.model = MyTableModel(tabledata, header, self) 
     #set table model 
     self.setModel(self.model) 


class ImageDelegate(QtGui.QStyledItemDelegate): 

    def __init__(self, parent): 
     print dir(self) 
     QtGui.QStyledItemDelegate.__init__(self, parent) 

    def paint(self, painter, option, index):   

     painter.fillRect(option.rect, QtGui.QColor(191,222,185)) 

     # path = "path\to\my\image.jpg" 
     self.path = "image.bmp" 

     image = QtGui.QImage(str(self.path)) 
     pixmap = QtGui.QPixmap.fromImage(image) 
     pixmap.scaled(50, 40, QtCore.Qt.KeepAspectRatio) 
     painter.drawPixmap(option.rect, pixmap) 

回答

0

在代表的繪製方法中,您可以通過index.model()訪問模型。然後,您可以查詢您的模型以獲取要顯示的數據(圖像)。例如,通過使用Qt.UserRole作爲模型的data函數。

另一個解決方案可能更容易,該模型的數據函數可以爲Qt.DecorationRole返回一個QIcon,QPixmap,QImage和QColor。在這種情況下,不需要代表。

作爲例子下面的代碼將在放中的圖標表的(僅)字段:

from PyQt4 import QtGui, QtCore 
import PyQt4.uic 

# using QtDesigner to just put a TableView in a Widget 
Form, Base = PyQt4.uic.loadUiType(r'TableView.ui') 

class TableModel(QtCore.QAbstractTableModel): 
    def __init__(self, parent=None): 
     super(TableModel,self).__init__(parent) 

    def rowCount(self, parent=QtCore.QModelIndex()): 
     return 1 

    def columnCount(self, parent=QtCore.QModelIndex()): 
     return 1 

    def data(self, index, role): 
     if index.isValid(): 
      if role==QtCore.Qt.DecorationRole: 
       return QtGui.QIcon("ChipScope.png") 
     return None 


class TableViewUi(Form, Base): 
    def __init__(self, parent=None): 
     Form.__init__(self) 
     Base.__init__(self,parent) 

    def setupUi(self, parent): 
     Form.setupUi(self,parent) 
     model = TableModel() 
     self.tableView.setModel(model) 

if __name__=="__main__": 
    app = QtGui.QApplication(sys.argv) 
    MainWindow = QtGui.QMainWindow() 
    ui = TableViewUi() 
    ui.setupUi(ui) 
    MainWindow.setCentralWidget(ui) 
    MainWindow.show() 
    sys.exit(app.exec_())