【问题标题】:using delegate for image in qtableview pyqt4 python?在 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) 

【问题讨论】:

    标签: python delegates pyqt4 qtableview


    【解决方案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_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-11
      • 2021-04-04
      • 1970-01-01
      • 2015-03-18
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多