我拼命地想弄清楚该怎么QDataWidgetMapper
工作。 因此,我写了源自自定义模型一个小演示应用QAbstractTableModel
。 如果我运行应用程序,我会承担,我得到下面的输出:
Firstname: Walter
Surname: Pinkman
不过,我得到:
Firstname: Jesse
Surname: Pinkman
我在想什么?
我也试图改变方向属性的QDataWidgetMapper
,后来我得到:
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_())