【发布时间】:2014-04-28 22:11:12
【问题描述】:
我拼命想弄清楚QDataWidgetMapper 是如何工作的。因此,我使用派生自QAbstractTableModel 的自定义模型编写了一个小型演示应用程序。如果我运行应用程序,我会假设我得到以下输出:
Firstname: Walter
Surname: Pinkman
但是,我得到:
Firstname: Jesse
Surname: Pinkman
我错过了什么?
我也尝试更改QDataWidgetMapper 的orientation-property,但后来我得到:
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_())
【问题讨论】:
标签: qt pyqt pyqt4 model-view