Sort QTableView in pyqt5

后端 未结 1 1727
梦如初夏
梦如初夏 2021-02-09 03:25

I want to sort a QTableView in PyQT5. I found an example that uses PyQT4, but in PyQT5 SIGNALs are not existing anymore. This is my example code

class MainWindow         


        
1条回答
  •  伪装坚强ぢ
    2021-02-09 03:54

    for those of you guys who wants to import pandas dataframe into qt model try this:

    class PandasModel(QtCore.QAbstractTableModel):
    
        def __init__(self, data, parent=None):
            """
    
            :param data: a pandas dataframe
            :param parent: 
            """
            QtCore.QAbstractTableModel.__init__(self, parent)
            self._data = data
            # self.headerdata = data.columns
    
    
        def rowCount(self, parent=None):
            return len(self._data.values)
    
        def columnCount(self, parent=None):
            return self._data.columns.size
    
        def data(self, index, role=QtCore.Qt.DisplayRole):
            if index.isValid():
                if role == QtCore.Qt.DisplayRole:
                    return str(self._data.values[index.row()][index.column()])
            return None
    
        def headerData(self, rowcol, orientation, role):
            # print(self._data.columns[rowcol])
            # print(self._data.index[rowcol])
            if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
                return self._data.columns[rowcol]
            if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
                return self._data.index[rowcol]
            return None
    
        def flags(self, index):
            flags = super(self.__class__, self).flags(index)
            flags |= QtCore.Qt.ItemIsEditable
            flags |= QtCore.Qt.ItemIsSelectable
            flags |= QtCore.Qt.ItemIsEnabled
            flags |= QtCore.Qt.ItemIsDragEnabled
            flags |= QtCore.Qt.ItemIsDropEnabled
            return flags
    
        def sort(self, Ncol, order):
            """Sort table by given column number.
            """
            try:
                self.layoutAboutToBeChanged.emit()
                self._data = self._data.sort_values(self._data.columns[Ncol], ascending=not order)
                self.layoutChanged.emit()
            except Exception as e:
                print(e)
    

    I have forgotten where I got the base pandasmodel, probably from here

    0 讨论(0)
提交回复
热议问题