此代码仅在同一行中显示相同的图像。如何在ImageDelegate中传递不同的图像路径?感谢
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 :(得分:0)
在委托的paint方法中,您可以通过index.model()
访问模型。然后,您可以在模型中查询要显示的数据(图像)。例如,通过将Qt.UserRole用于模型的data
函数。
另一个可能更容易的解决方案是,模型的数据函数可以为Qt.DecorationRole返回QIcon,QPixmap,QImage和QColor之一。在这种情况下,不需要代表。
作为示例,以下代码将在表的(仅)字段中放入Icon:
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_())