如何在QAbstractTableModel中设置数据

use*_*240 13 qt qtableview qabstracttablemodel

我需要用Qt实现一个表.

我相信我会使用这个模型使用QTableView来起诉QAbstractTableModel.

我知道我必须编辑模型的rowCount(),columnCount()和data()函数.

但是,我不明白如何在模型中精确设置数据,以便data()函数可以检索它.

为此目的提供了setData()函数吗?我已经看到它需要EditRole作为其参数,我不想要,因为我不希望我的表可编辑.

那么,如何使用data()函数在模型中"设置"数据,或者让模型获得数据?

另外,如何调用data()函数,即谁调用它以及需要调用它的位置?

请帮我解决一下这个.

谢谢.

dsc*_*ulz 19

实际数据如何保存在内存中,从数据存储中生成或查询完全取决于您.如果是静态数据,则可以使用Qt容器类或自定义数据结构.

您只需重新实现setData()可编辑模型的方法.

您需要在不可编辑的QAbstractTableModel子类中实现4种方法:

  • int rowCount()
  • int columnCount()
  • QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole )
  • QVariant data(const QModelIndex & index, int role = Qt::DisplayRole)

从视图中调用这些方法,通常是QTableView实例.前两个方法应该返回表的维度.例如,如果rowCount()返回10columnCount()返回4,则视图将调用该data()方法40次(每个单元一次),询问模型内部数据结构中的实际数据.

例如,假设您已retrieveDataFromMarsCuriosity()在模型中实现了自定义插槽.此插槽填充数据结构并连接到QPushButton实例,因此您可以通过单击按钮获取新数据.现在,您需要让视图知道何时更改数据,以便可以正确更新.这就是为什么你需要发出beginRemoveRows(),endRemoveRows(),beginInsertRows(),endInsertRows()和其列同行.

Qt文档有你需要了解这一切.


Mic*_*ann 6

您不需要使用setData(...). 相反,你需要在子类QAbstractTableModel中的这样一种方式,它的方法rowCount()columnCount()data(index)和潜在的headerData(section, horizontalOrVertical)回报要显示的数据。这是一个基于 PyQt5 的示例:

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

headers = ["Scientist name", "Birthdate", "Contribution"]
rows =    [("Newton", "1643-01-04", "Classical mechanics"),
           ("Einstein", "1879-03-14", "Relativity"),
           ("Darwin", "1809-02-12", "Evolution")]

class TableModel(QAbstractTableModel):
    def rowCount(self, parent):
        # How many rows are there?
        return len(rows)
    def columnCount(self, parent):
        # How many columns?
        return len(headers)
    def data(self, index, role):
        if role != Qt.DisplayRole:
            return QVariant()
        # What's the value of the cell at the given index?
        return rows[index.row()][index.column()]
    def headerData(self, section, orientation, role):
        if role != Qt.DisplayRole or orientation != Qt.Horizontal:
            return QVariant()
        # What's the header for the given column?
        return headers[section]

app = QApplication([])
model = TableModel()
view = QTableView()
view.setModel(model)
view.show()
app.exec_()
Run Code Online (Sandbox Code Playgroud)

它取自此GitHub 存储库并显示下表:

QAbstractTableModel 示例