QAbstractTableModel不正确地追加或排序我的表模型

时间:2018-08-03 19:19:59

标签: python-3.x pyqt5 qabstracttablemodel

我正在尝试使用此抽象模型通过tableview运行。有两个问题。

  • PandasModel中的测试功能不添加任何内容
  • 排序列给我带来了重大问题,我无法按降序对列0或索引进行排序。 有人对这两个问题有任何建议吗?

下面的代码有效,并且只会显示1、1、1、1、1、1的一行

对于排序功能,我是否需要手动编辑QPersistent Model索引才能真正进行排序?因为当我对索引进行排序时,只是发生了变化,但数据保持不变。

import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets

global df
list = [[1,1,1,1,1]]
df = pd.DataFrame(list)

class PandasModel(QtCore.QAbstractTableModel): 
    def __init__(self, df = pd.DataFrame(), parent=None): 
        QtCore.QAbstractTableModel.__init__(self, parent=parent)
        self._df = df

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if orientation == QtCore.Qt.Horizontal:
            try:
                return self._df.columns.tolist()[section]
            except (IndexError, ):
                return QtCore.QVariant()
        elif orientation == QtCore.Qt.Vertical:
            try:
                # return self.df.index.tolist()
                return self._df.index.tolist()[section]
            except (IndexError, ):
                return QtCore.QVariant()

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if not index.isValid():
            return QtCore.QVariant()


        return QtCore.QVariant(str(self._df.ix[index.row(), index.column()]))


    def setData(self, index, value, role):
        row = self._df.index[index.row()]
        col = self._df.columns[index.column()]
        if hasattr(value, 'toPyObject'):
            # PyQt4 gets a QVariant
            value = value.toPyObject()
        else:
            # PySide gets an unicode
            dtype = self._df[col].dtype
            if dtype != object:
                value = None if value == '' else dtype.type(value)
        self._df.set_value(row, col, value)
        return True

    def rowCount(self, parent=QtCore.QModelIndex()): 
        return len(self._df.index)

    def columnCount(self, parent=QtCore.QModelIndex()): 
        return len(self._df.columns)
    def test(self):
        self.layoutAboutToBeChanged.emit()

        self._df.append([1,1,1,1,1])
        self.layoutChanged.emit()
        print("sucess")


    def sort(self, column, order):
       colname = self._df.columns.tolist()[column]
       self.layoutAboutToBeChanged.emit()
       self._df.sort_values(colname, ascending= order == QtCore.Qt.AscendingOrder, inplace=True)
       self._df.reset_index(inplace=True, drop=True)
       self.layoutChanged.emit()   


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(735, 281)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tableView = QtWidgets.QTableView(self.centralwidget)
        self.tableView.setGeometry(QtCore.QRect(10, 10, 711, 241))
        self.tableView.setObjectName("tableView")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.tableView.setModel(model)

        self.tableView.resizeColumnToContents(0)
        self.tableView.resizeColumnToContents(1)
        self.tableView.resizeColumnToContents(2)
        self.tableView.resizeColumnToContents(3)
        self.tableView.resizeColumnToContents(4)
        self.tableView.resizeColumnToContents(5)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))




if __name__ == "__main__":
    global model
    import sys


    model = PandasModel(df)
    model.test()
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_()) 

0 个答案:

没有答案