how to add widgets in every a qtableView cell with a MVC design?

北战南征 提交于 2019-12-11 15:45:00

问题


Here is a simple example of a qtableView where every cell have a different item. In the example here i used numbers, but ultimately i wish to display animated gifs for every cells. I wish to keep the MVC design and insert a custom widget proceduraly.

import random
import math
from PyQt4 import QtCore, QtGui

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data, columns, parent=None):
        super(TableModel, self).__init__(parent)
        self._columns = columns
        self._data = data[:]

    def rowCount(self, parent=QtCore.QModelIndex()): 
        if parent.isValid() or self._columns == 0:
            return 0
        return math.ceil(len(self._data )*1.0/self._columns)

    def columnCount(self, parent=QtCore.QModelIndex()): 
        if parent.isValid():
            return 0
        return self._columns

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if not index.isValid(): 
            return
        if role == QtCore.Qt.DisplayRole: 
            try:
                value = self._data[ index.row() * self._columns + index.column() ]
                return value
            except:
                pass

class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        data = [random.choice(range(10)) for i in range(20)]

        l = QtGui.QHBoxLayout(self)
        splitter = QtGui.QSplitter()
        l.addWidget(splitter)

        tvf = QtGui.QTableView()
        model = TableModel(data, 3, self)
        tvf.setModel(model)

        splitter.addWidget( tvf )


if __name__=="__main__":
    import sys
    a=QtGui.QApplication(sys.argv)
    w=Widget()
    w.show()
    sys.exit(a.exec_())

After reading a bit more and with the help of @eyllanesc, i understand that there is 2 ways of achieving this: delegates or itemWidget. It seem that delegates won't work for me since it's not possible to insert widget into cells that way. ItemWidget seems the way to go but this is not MVC compatible ? i do not wish to loop the function to insert into the table...

is there a third way ?

来源:https://stackoverflow.com/questions/52552680/how-to-add-widgets-in-every-a-qtableview-cell-with-a-mvc-design

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!