Fastest way to populate QTableView from Pandas data frame

后端 未结 7 1262
面向向阳花
面向向阳花 2020-11-27 16:54

I\'m very new to PyQt and I am struggling to populate a QTableView control.

My code is the following:

def data_frame_to_ui(self, data_frame):
                


        
7条回答
  •  清歌不尽
    2020-11-27 17:31

    Here is fully working copy-paste example for PyQT5 based on @Frederick Li answer with minor modifications.

    from PyQt5 import QtGui, QtWidgets
    from PyQt5.QtCore import Qt
    import sys
    import pandas as pd
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, *args, obj=None, **kwargs):
            super(MainWindow, self).__init__(*args, **kwargs)
    
            self.centralwidget = QtWidgets.QWidget(self)
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
            self.centralwidget.setSizePolicy(sizePolicy)
    
            self.pdtable = QtWidgets.QTableView(self.centralwidget)
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
            self.pdtable.setSizePolicy(sizePolicy)
    
            dataPD = [['tom', 10.0, 180.3], ['nick', 15.0, 175.7], ['juli', 14.0, 160.6]]
            df = pd.DataFrame(dataPD, columns=['Name', 'Age', 'Height'])
            print(df.dtypes)
            self.model = PandasTableModel(df)
            self.pdtable.setModel(self.model)
    
            self.setCentralWidget(self.centralwidget)
    
    
    class PandasTableModel(QtGui.QStandardItemModel):
        def __init__(self, data, parent=None):
            QtGui.QStandardItemModel.__init__(self, parent)
            self._data = data
            for row in data.values.tolist():
                data_row = [ QtGui.QStandardItem("{}".format(x)) for x in row ]
                self.appendRow(data_row)
            return
    
        def rowCount(self, parent=None):
            return len(self._data.values)
    
        def columnCount(self, parent=None):
            return self._data.columns.size
    
        def headerData(self, x, orientation, role):
            if orientation == Qt.Horizontal and role == Qt.DisplayRole:
                return self._data.columns[x]
            if orientation == Qt.Vertical and role == Qt.DisplayRole:
                return self._data.index[x]
            return None
    
    
    if __name__ == "__main__":
        app  = QtWidgets.QApplication(sys.argv)
        app.setStyle("Fusion")
        main = MainWindow()
        main.show()
        main.resize(600, 400)
        sys.exit(app.exec_())
    

提交回复
热议问题