如何在 QAbstractTableModel 更改上更新 QTableView [英] How to update QTableView on QAbstractTableModel Change

查看:59
本文介绍了如何在 QAbstractTableModel 更改上更新 QTableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 QTableViewQAbstractTableModel 时,有时 QTableView 不会随着 QAbstractTableModel 数据中发生的变化而更新.为了强制"或触发视图更新,我使用 QAbstractTableModel 的 self.layoutChanged.emit() 方法.

虽然它有效,但我注意到这种方法可能会导致一些不稳定甚至崩溃.QAbstractTableModel 发生变化时,是否有其他方法可以更新 QTableView?

解决方案

基本上,你可以将一个函数连接到模型 dataChanged 信号/事件,或者你可以在用于修改模型的函数中插入这个信号,如果你已经实现了一个.

第一个选项可能如下所示,在您的模型类中,

self.dataChanged.connect(self.view.refresh)

其中 refresh() 是您视图中的自定义槽,它触发一个简单的 self.update(),否则您需要处理信号发送的参数(受影响的父 QModelIndex).<小时>

第二个选项需要使用 QModelIndex 发出信号,当您在模型类中应用一些更改时在函数中调用它:

self.dataChanged.emit(self.index(X, Y), self.index(X, Y))

其中 X 和 Y 代表已更改数据在表格中的位置

第三个参数role是一个选项,即可以指定DisplayRole,否则所有角色都可以更新.

While working with the QTableView and QAbstractTableModel there are times when the QTableView is not updated with the changes taking place in QAbstractTableModel's data. In order to "enforce" or to trigger the view update I use QAbstractTableModel's self.layoutChanged.emit() method.

While it works I have noticed this method may cause some instability and even a crash. I wonder if there is an alternative way to update the QTableView when the QAbstractTableModel changes?

解决方案

Basically, you can connect a function to the model dataChanged signal/event, or you can insert this signal inside the function used to modify the model if you have implemented one.

The first option could be like below, in your model class,

self.dataChanged.connect(self.view.refresh) 

where refresh() is a custom slot in your view which trigger a simple self.update(), otherwise you need to handle the parameters send by the signal (affected parents QModelIndex).


The second option needs to emit the signal with QModelIndex, call this in the function when you apply some changes in the model class :

self.dataChanged.emit(self.index(X, Y), self.index(X, Y)) 

where X and Y represent the position of the changed data in your table

The third parameter role is an option, i.e. you can specify the DisplayRole, otherwise all roles can be updated.

这篇关于如何在 QAbstractTableModel 更改上更新 QTableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆