文章目录
映射器
将view
里面列的值映射岛QWidget
上,和delegate
的作用差不多,不过mapper
是和view
分开,而delagate
在view
上。
- 创建:
QDataWidgetMapper
- 设置模型:
setModel
- 绑定数据:
addMapping
- 绑定变换:
view.selectionModel().currentRowChanged.connect(mapper.setCurrentModelIndex)
如果使用proxy模型,需要多index先做一个映射。
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtWidgets import QApplication, QDataWidgetMapper, QLineEdit, QPushButton, QSpinBox, QWidget, QVBoxLayout, \
QListView, QFormLayout, QTreeView, QTableView
from PyQt5.QtCore import QSortFilterProxyModel, QModelIndex
class Demo(QWidget):
def __init__(self):
super(Demo, self).__init__()
self.__settingWindow()
self.__buildUI()
self.__createModel()
# ================== 辅助函数 ================== #
def __settingWindow(self):
self.resize(250, 300)
def __buildUI(self):
vbox = QVBoxLayout(self)
self.listView = QTableView()
self.listView.setSortingEnabled(True)
vbox.addWidget(self.listView)
form = QFormLayout()
form.setHorizontalSpacing(50)
vbox.addLayout(form)
self.editName = QLineEdit()
self.editSex = QLineEdit()
form.addRow('姓名', self.editName)
form.addRow('性别', self.editSex)
def __initModelData(self):
# 初始化数据
info = [['小明', '男'],
['小呆', '女'],
['白衣服', '男']]
for i in range(3):
for j in range(2):
index = self.model.index(i, j)
self.model.setData(index, info[i][j])
def __createModel(self):
self.model = QStandardItemModel(3, 2)
self.proxyModel = QSortFilterProxyModel()
self.proxyModel.setSourceModel(self.model)
self.listView.setModel(self.proxyModel)
self.__initModelData()
mapper = QDataWidgetMapper(self)
mapper.setModel(self.model)
mapper.addMapping(self.editName, 0)
mapper.addMapping(self.editSex, 1)
self.mapper = mapper
self.listView.selectionModel().currentRowChanged.connect(self.__setCurrentModelIndex)
# self.listView.selectionModel().currentRowChanged.connect(self.mapper.setCurrentModelIndex)
def __setCurrentModelIndex(self, currentIndex: QModelIndex, prevIndex):
currentIndex = self.proxyModel.mapToSource(currentIndex)
parent = currentIndex.parent()
self.mapper.setRootIndex(parent)
self.mapper.setCurrentModelIndex(currentIndex)
if __name__ == '__main__':
app = QApplication([])
w = Demo()
w.show()
app.exec_()