[英]Update multiple Qt models based on a single data source
我想觸發多個模型更新,從而基於原始數據源更新(如對象列表)觸發多個視圖更新。 數據和多個模型之間的映射如何工作?
例如:
我有多個Measurements
列表,其中包含size
、 color
和weight
等屬性
Measurements
值size
的QListView
的接口size
和color
的QTableView
的接口然后我觸發對我的原始數據的更新。 它可以來自上面提到的連接模型之一或來自外部更新。 如何將此更改添加到我的所有關聯模型?
我正在使用 python 和 Pyside2 但答案可以在 C++
因此,正如@Frank Osterfeld 在他的評論中所說,可以將所有數據存儲在 model (在我的情況下為QAbstractTableModel
)中,然后過濾掉您在各自視圖中不需要的列。
為此,我使用了QSortFilterProxyModel
並覆蓋了filterAcceptsColumn()
方法。
這是一個例子:
class MyModel(QAbstractTableModel):
def __init__(self):
super().__init__()
self.data = []
... # here are all the things you usually define in an abstract model
class MyProxyModelA(QSortFilterProxyModel):
def filterAcceptsColumn(self, source_column: int, source_parent: QModelIndex) -> bool:
""" This filters any column that returns true """
return source_column != 2
class MyProxyModelB(QSortFilterProxyModel):
def filterAcceptsColumn(self, source_column: int, source_parent: QModelIndex) -> bool:
""" This filters any column that returns true """
return source_column == 2
在我看來:
model = MyModel() # I put this here for the sake of this example
class MyWidgetA(QWidget):
def __init__(self):
super().__init__()
self.ui = Ui_Form()
self.ui.setupUi(self)
self.table = QTableView()
self.proxy = MyProxyModelA()
self.proxy.setSourceModel(model)
self.table.setModel(self.proxy)
self.ui.layout.addWidget(self.table)
class MyWidgetB(QWidget):
def __init__(self):
super().__init__()
self.ui = Ui_Form()
self.ui.setupUi(self)
self.table = QTableView()
self.proxy = MyProxyModelB()
self.proxy.setSourceModel(model)
self.table.setModel(self.proxy)
self.ui.layout.addWidget(self.table)
現在您可以從 model 和您的視圖的自動同步中受益,無論您何時通過MyWidgetA
或MyWidgetB
修改它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.