我拼命想弄清楚QDataWidgetMapper
是如何运作的。因此,我使用从QAbstractTableModel
派生的自定义模型编写了一个小型演示应用程序。如果我运行应用程序,我会假设,我得到以下输出:
Firstname: Walter
Surname: Pinkman
但是,我得到了:
Firstname: Jesse
Surname: Pinkman
我错过了什么?
我还尝试更改QDataWidgetMapper
的{{3}},但后来我得到了:
Firstname: White
Surname: Pinkman
示例:
#!/usr/bin/env python
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class myModel(QtCore.QAbstractTableModel):
def __init__(self, parent = None):
QtCore.QAbstractTableModel.__init__(self, parent)
self.lst = [
["Walter", "White"],
["Jesse", "Pinkman"]
]
def columnCount(self, parent = QtCore.QModelIndex()):
return len(self.lst[0])
def rowCount(self, parent = QtCore.QModelIndex()):
return len(self.lst)
def data(self, index, role = QtCore.Qt.DisplayRole):
row = index.row()
col = index.column()
if role == QtCore.Qt.EditRole:
return self.lst[row][col]
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
model = myModel(self)
# Set up the widgets.
firstnameLabel = QtGui.QLabel("Firstname:")
surnameLabel = QtGui.QLabel("Surname:")
firstname = QtGui.QLabel(self)
surname = QtGui.QLabel(self)
# Set up the mapper.
mapper = QtGui.QDataWidgetMapper(self)
mapper.setModel(model)
#map first row, first column to "firstname"
mapper.addMapping(firstname, 0, "text")
mapper.toFirst()
#map first row, second column to "surname"
mapper.addMapping(surname, 1, "text")
mapper.toNext()
#set up layout
layout = QtGui.QGridLayout()
layout.addWidget(firstnameLabel, 0, 0)
layout.addWidget(firstname, 0, 1)
layout.addWidget(surnameLabel, 1, 0)
layout.addWidget(surname, 1, 1)
self.setLayout(layout)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
一切都很好。这是因为QDataWidgetMapper
为所有连接的小部件设置数据,因此使用toNext
为所有映射的小部件设置第二行的数据。