【问题标题】:PyQt: Adding rows to QTableView using QAbstractTableModelPyQt:使用 QAbstractTableModel 向 QTableView 添加行
【发布时间】:2014-05-12 13:46:24
【问题描述】:

我是 Qt 编程的超级新手。我正在尝试制作一个简单的表格,可以通过单击按钮添加行。我可以很好地实现表格,但似乎无法让更新的数据显示在表格上。我相信我的问题源于我似乎无法使用按钮正确调用任何类型的“更改数据”方法。我在网上尝试了几种不同的解决方案,所有这些都导致了 4 岁的死胡同。到目前为止我所拥有的是基本结构,我只是不知道如何使用新数据更新表。

这是基本视图

我已经设置了一些测试数据。

在最终的实现中,表格将开始为空,我想追加行并将它们显示在表格视图中。

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        # create table
        self.get_table_data()
        self.table = self.createTable()

        # layout
        self.layout = QVBoxLayout()

        self.testButton = QPushButton("test")
        self.connect(self.testButton, SIGNAL("released()"), self.test)        

        self.layout.addWidget(self.testButton)
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)

    def get_table_data(self):
        self.tabledata = [[1234567890,2,3,4,5],
                          [6,7,8,9,10],
                          [11,12,13,14,15],
                          [16,17,18,19,20]]

    def createTable(self):
        # create the view
        tv = QTableView()

        # set the table model
        header = ['col_0', 'col_1', 'col_2', 'col_3', 'col_4']
        tablemodel = MyTableModel(self.tabledata, header, self)
        tv.setModel(tablemodel)

        # set the minimum size
        tv.setMinimumSize(400, 300)

        # hide grid
        tv.setShowGrid(False)

        # hide vertical header
        vh = tv.verticalHeader()
        vh.setVisible(False)

        # set horizontal header properties
        hh = tv.horizontalHeader()
        hh.setStretchLastSection(True)

        # set column width to fit contents
        tv.resizeColumnsToContents()

        # set row height
        tv.resizeRowsToContents()

        # enable sorting
        tv.setSortingEnabled(False)

        return tv

    def test(self):
        self.tabledata.append([1,1,1,1,1])
        self.emit(SIGNAL('dataChanged()'))
        print 'success'

class MyTableModel(QAbstractTableModel):
    def __init__(self, datain, headerdata, parent=None):
        """
        Args:
            datain: a list of lists\n
            headerdata: a list of strings
        """
        QAbstractTableModel.__init__(self, parent)
        self.arraydata = datain
        self.headerdata = headerdata

    def rowCount(self, parent):
        return len(self.arraydata)

    def columnCount(self, parent):
        if len(self.arraydata) > 0: 
            return len(self.arraydata[0]) 
        return 0

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()
        return QVariant(self.arraydata[index.row()][index.column()])

    def setData(self, index, value, role):
        pass         # not sure what to put here

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

    def sort(self, Ncol, order):
        """
        Sort table by given column number.
        """
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.arraydata = sorted(self.arraydata, key=operator.itemgetter(Ncol))       
        if order == Qt.DescendingOrder:
            self.arraydata.reverse()
        self.emit(SIGNAL("layoutChanged()"))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

【问题讨论】:

  • 感谢您提供示例代码!非常有帮助!
  • 同意.. 您问题中的代码示例是对许多其他问题的回答。

标签: python button row qtableview qabstracttablemodel


【解决方案1】:

当模型的基础数据发生变化时,模型应该发出layoutChangedlayoutAboutToBeChanged,以便正确更新视图(还有dataChanged,如果您想更新特定范围的单元格)。

所以你只需要这样的东西:

    def test(self):
        self.tabledata.append([1,1,1,1,1])
        self.table.model().layoutChanged.emit()
        print 'success'

【讨论】:

  • 模型中不需要 setData() 吗?我查看了所有文档,并且不断看到需要使用 setData() 或 insertRows() 等的参考资料。问题是我不是 100% 确定如何实现 setData() 方法或更重要的是如何实现称它为。 - 编辑:嗯,我刚刚尝试了你的编辑,没有 setData() 方法它工作得很好,所以我想它毕竟不需要!非常感谢您的帮助!
  • 当你想要一个可编辑的网格时,通常你需要实现 setData() ,以便在你的模型中更新正确的值。例如:def setData(self, index, value, role = Qt.EditRole): if role == Qt.EditRole: setattr(self.arraydata[index.row()], self.columns[index.column()], value) self.dataChanged.emit(index, index, ()) return True else: return False
  • 从技术上讲这是行不通的,因为self.tabledata 只是一个list,并没有真正连接到QTableView。
【解决方案2】:

我已让您的表引用类变量而不是实例变量,因此您几乎可以在代码中的任何位置编辑表的数据。

# First access the data of the table
self.tv_model = self.tv.model()

其次,我使用了 pandas-dataframe-editing 类型的方法。 假设您要添加的数据单独存储在一个变量中:

# These can be whatever, but for consistency, 
# I used the data in the OP's example

new_values = [1, 1, 1, 1, 1]

下一步可以采用不同的方法,具体取决于是将数据添加到表中,还是更新现有值。将数据添加为新行如下所示。

# The headers should also be a class variable, 
# but I left it as the OP had it

header = ['col_0', 'col_1', 'col_2', 'col_3', 'col_4']

# There are multiple ways of establishing what the row reference should be,
# this is just one example how to add a new row

new_row = len(self.tv_model.dataFrame.index)

for i, col in enumerate(header):
    self.tv_model.dataFrame.loc[new_row, col] = new_values[i]

由于self.tv_model是对表实际数据的引用, 发出以下信号将更新数据,或将其“提交”到模型, 可以这么说。

self.tv_model.layoutChanged.emit()

【讨论】:

    【解决方案3】:

    QAbstractTableModel 有两种特殊方法(beginInsertRows()endInsertRows())。

    您可以在自定义模型中添加 api-point。例如:

        def insertGuest(self, guest):
            self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
            self.guestsTableData.append(guest)
            self.endInsertRows()
    

    【讨论】:

      猜你喜欢
      • 2013-07-15
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2021-08-27
      • 2021-03-26
      • 1970-01-01
      相关资源
      最近更新 更多