How is it that
self.model = MyTableModel(self, [User('Mary', '12345'), User('John', 'qwerty')], ['name', 'password'])
can pass object instanceUser('Mary', '12345')
toMyTableModel()
when I don't seedef __init__(self, parent, rows, columns)
set up to take it? From what I know, rows and columns are arguments to take info from the widget object and not a outside non widget object.What does the last part
['name', 'password']
do when given to MyTableModel()?Actually, I want just one instance of User() and have the model class update User() object instance if the human changes the lineEdit widget. since "mary" and "12345" in self.model = MyTableModel(self, [User('Mary', '12345')] are hardcoded values, how do I use the values of the lineEdit widgets instead in User(parameter, parameter)?
from PyQt4 import QtCore, QtGui import sys class User(): def __init__(self, name, password): self.name = name self.password = password class MyTableModel(QtCore.QAbstractTableModel): def __init__(self, parent, rows, columns): super().__init__(parent) self.rows = rows self.columns = columns def columnCount(self, index): return len(self.columns) def rowCount(self, index): return len(self.rows) def data(self, index, role): if index.isValid(): if (role == QtCore.Qt.DisplayRole) or (role == QtCore.Qt.EditRole): attr_name = self.columns[index.column()] row = self.rows[index.row()] return getattr(row, attr_name) def flags(self, index): if not index.isValid(): return QtCore.Qt.ItemIsEnabled else: return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable def setData(self, index, value, role=QtCore.Qt.EditRole): if index.isValid() and role == QtCore.Qt.EditRole: attr_name = self.columns[index.column()] row = self.rows[index.row()] setattr(row, attr_name, value) class MyWindow(QtGui.QWidget): def __init__(self): super(MyWindow, self).__init__() self.setLayout(QtGui.QFormLayout(self)) self.user_edit = QtGui.QLineEdit(self) self.password_edit = QtGui.QLineEdit(self) self.mapper = QtGui.QDataWidgetMapper(self) self.model = MyTableModel(self, [User('Mary', '12345'), User('John', 'qwerty')], ['name', 'password']) self.mapper.setModel(self.model) self.mapper.addMapping(self.user_edit, 0) self.mapper.addMapping(self.password_edit, 1) self.mapper.toFirst() self.layout().addRow("User name:", self.user_edit) self.layout().addRow("Password:", self.password_edit) self.btnPrevious = QtGui.QPushButton("Previous", self) self.btnNext = QtGui.QPushButton("Next",self) self.layout().addWidget(self.btnPrevious) self.layout().addWidget(self.btnNext) self.btnPrevious.clicked.connect(self.mapper.toPrevious) self.btnNext.clicked.connect(self.mapper.toNext) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) win = MyWindow() win.show() app.exec_()