18

我想在 PyQt 表中显示熊猫数据框。我在这方面取得了一些进展,但无法正确派生 Table Model 类。对此的任何帮助将不胜感激。

** 请注意此处的完整示例代码**

我正在努力生成一个有效的 QtCore.QAbstractTableModel 派生类。继之前关于 QItemDelegates 的问题之后,我正在尝试从 Pandas DataFrame 生成表模型以插入真实数据。我在这里有工作示例代码,但是如果我在 Widget 类(ln 152)中用 TableModel2 替换我的 TableModel,我无法让表格显示。

class TableModel2(QtCore.QAbstractTableModel): 
    def __init__(self, parent=None, *args): 
        super(TableModel2, self).__init__()
        #QtCore.QAbstractTableModel.__init__(self, parent, *args)
        self.datatable = None
        self.headerdata = None
        self.dataFrame = None
        self.model = QtGui.QStandardItemModel(self)

    def update(self, dataIn):
        print 'Updating Model'
        self.datatable = dataIn
        print 'Datatable : {0}'.format(self.datatable)
        headers = dataIn.columns.values
        header_items = [
                    str(field)
                    for field in headers
        ]
        self.headerdata = header_items
        print 'Headers'
        print self.headerdata

        for i in range(len(dataIn.index.values)):
            for j in range(len(dataIn.columns.values)):
                #self.datatable.setItem(i,j,QtGui.QTableWidgetItem(str(df.iget_value(i, j))))
                self.model.setItem(i,j,QtGui.QStandardItem(str(dataIn.iget_value(i, j))))

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

    def columnCount(self, parent=QtCore.QModelIndex()):
        return len(self.datatable.columns.values) 

    def data(self, index, role=QtCore.Qt.DisplayRole): 
        if not index.isValid(): 
            return QtCore.QVariant()
        elif role != QtCore.Qt.DisplayRole: 
            return QtCore.QVariant() 
        #return QtCore.QVariant(self.model.data(index)) 
            return QtCore.QVariant(self.model.data(index)) 

    def headerData(self, col, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        return QtCore.QVariant(self.headerdata[col])

    def setData(self, index, value, role=QtCore.Qt.DisplayRole):
        print "setData", index.row(), index.column(), value

    def flags(self, index):
        if (index.column() == 0):
            return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled
        else:
            return QtCore.Qt.ItemIsEnabled 

我正在尝试创建模型,然后将其添加到视图中,如下所示:

class Widget(QtGui.QWidget):
    """
    A simple test widget to contain and own the model and table.
    """
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        l=QtGui.QVBoxLayout(self)
        cdf = self.get_data_frame()
        self._tm=TableModel(self)
        self._tm.update(cdf)
        self._tv=TableView(self)
        self._tv.setModel(self._tm)
        for row in range(0, self._tm.rowCount()):
            self._tv.openPersistentEditor(self._tm.index(row, 0))
        l.addWidget(self._tv)

    def get_data_frame(self):
        df = pd.DataFrame({'Name':['a','b','c','d'], 
        'First':[2.3,5.4,3.1,7.7], 'Last':[23.4,11.2,65.3,88.8], 'Class':[1,1,2,1], 'Valid':[True, True, True, False]})
        return df

感谢您的关注!

注意:编辑 2 我已将 QStandardItemModel 合并到 TableModel2 中。在@mata 的评论之后还删除了 dataFrameToQtTable 函数。这越来越近了,但仍然无法正常工作。

4

4 回答 4

17

好的,我已经通过上述建议和 Summerfield 的 Rapid GUI 书的一些帮助解决了这个问题。QAbstractTableModel 中不存在基础模型。只需要重写三个函数,数据可以以任何用户定义的格式存储,只要在数据调用中返回即可。

一个非常简单的实现可能是:

class TableModel(QtCore.QAbstractTableModel): 
    def __init__(self, parent=None, *args): 
        super(TableModel, self).__init__()
        self.datatable = None

    def update(self, dataIn):
        print 'Updating Model'
        self.datatable = dataIn
        print 'Datatable : {0}'.format(self.datatable)

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

    def columnCount(self, parent=QtCore.QModelIndex()):
        return len(self.datatable.columns.values) 

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.DisplayRole:
            i = index.row()
            j = index.column()
            return '{0}'.format(self.datatable.iget_value(i, j))
        else:
            return QtCore.QVariant()

    def flags(self, index):
        return QtCore.Qt.ItemIsEnabled

这使您能够在 Qt 视图中查看任何兼容的数据框。

我在这里更新了要点

如果您还需要这样做,这应该可以让您快速进行。

于 2013-07-17T14:37:27.170 回答
2

这可能是你的问题:

def rowCount(self, parent=QtCore.QModelIndex()):
    if type(self.datatable) == pd.DataFrame:
    ...


def columnCount(self, parent=QtCore.QModelIndex()):
    if (self.datatable) == pd.DataFrame:
    ...

您将您设置datatable为 a QTableWidgetin dataFrameToQtTable,所以它不能是 a pd.DataFrame,您的方法将始终返回 0。

如果没有类型检查,您将立即发现问题。您是否真的想默默地忽略所有类型不匹配的情况(如果它不遵循您期望的相同界面,最好让它引发错误)?在大多数情况下,类型检查是不必要的。

于 2013-07-17T11:15:07.247 回答
1

Pandas 0.13 提供了一个实验性功能:

PySide 支持 qtpandasDataFrameModelDataFrameWidget

https://github.com/pydata/pandas/blob/master/doc/source/faq.rst

您可以使用添加此功能

from pandas.sandbox.qtpandas import DataFrameModel, DataFrameWidget
于 2014-03-04T08:06:52.707 回答
0

这是一个最小的QAbstractItemModel实现来展示它是如何工作的。

# Created by BaiJiFeiLong@gmail.com at 2022/3/2
from __future__ import annotations

import typing

from PySide2 import QtWidgets, QtCore


class TreeNode(object):
    columns: typing.Sequence[str]
    children: typing.Sequence[TreeNode]
    parent: typing.Union[None, TreeNode]

    def __init__(self, columns, children) -> None:
        self.columns = columns
        self.children = children
        self.parent = None
        for child in self.children:
            child.parent = self

    def row(self):
        return -1 if self.parent is None else self.parent.children.index(self)


class TreeModel(QtCore.QAbstractItemModel):
    def __init__(self, parent: typing.Optional[QtCore.QObject] = None) -> None:
        super().__init__(parent)
        self._rootNode = TreeNode(columns=["Name", "Description"], children=[
            TreeNode(columns=["Animal", "The Animal"], children=[
                TreeNode(columns=["Ant", "The Ant"], children=[]),
                TreeNode(columns=["Bee", "The Bee"], children=[]),
                TreeNode(columns=["Cat", "The Cat"], children=[]),
            ]),
            TreeNode(columns=["Plant", "The Plant"], children=[
                TreeNode(columns=["Apple", "The Apple"], children=[]),
                TreeNode(columns=["Banana", "The Banana"], children=[]),
            ]),
        ])

    def _indexToNode(self, index: QtCore.QModelIndex):
        return index.internalPointer() if index.isValid() else self._rootNode

    def index(self, row: int, column: int, parent: QtCore.QModelIndex = ...) -> QtCore.QModelIndex:
        return self.createIndex(row, column, self._indexToNode(parent).children[row])

    def parent(self, child: QtCore.QModelIndex) -> QtCore.QModelIndex:
        parent = self._indexToNode(child).parent
        return QtCore.QModelIndex() if parent is None else self.createIndex(parent.row(), 0, parent)

    def rowCount(self, parent: QtCore.QModelIndex = ...) -> int:
        return len(self._indexToNode(parent).children)

    def columnCount(self, parent: QtCore.QModelIndex = ...) -> int:
        return len(self._indexToNode(parent).columns)

    def data(self, index: QtCore.QModelIndex, role: int = ...) -> typing.Any:
        if role == QtCore.Qt.ItemDataRole.DisplayRole:
            return self._indexToNode(index).columns[index.column()]

    def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = ...) -> typing.Any:
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return self._rootNode.columns[section]


app = QtWidgets.QApplication()
treeView = QtWidgets.QTreeView()
treeView.setModel(TreeModel())
treeView.show()
app.exec_()
于 2022-03-02T06:22:40.420 回答