在 qtableview pyqt4 python 中使用图像委托?

Posted

技术标签:

【中文标题】在 qtableview pyqt4 python 中使用图像委托?【英文标题】:using delegate for image in qtableview pyqt4 python? 【发布时间】:2014-01-25 00:40:57 【问题描述】:

此代码只会在同一行中显示相同的图像。如何在 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) 

【问题讨论】:

【参考方案1】:

在委托的绘制方法中,您可以通过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_())

【讨论】:

以上是关于在 qtableview pyqt4 python 中使用图像委托?的主要内容,如果未能解决你的问题,请参考以下文章

PyQt4 qTableView 对齐

如何在 Pyqt4 中设置 QTableView 标头名称

基于 PyQt4 QTableView 模型

如何在pyqt4的右侧对齐qtableview行?

PyQt4中的QTableView选定元素

如何将 QLineEdit 放入 QTableView 单元格 PyQt4?