Frage

I am desperately trying to figure out how the QDataWidgetMapper works. Therefore, I wrote a small demo application with a custom model derived from QAbstractTableModel. If I run the application, I would assume, that I get the following output:

Firstname: Walter
Surname: Pinkman

However, I get:

Firstname: Jesse 
Surname: Pinkman

What am I missing?

I also tried to change the orientation-property of QDataWidgetMapper, but then I get:

Firstname: White
Surname: Pinkman 

example:

#!/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_())
War es hilfreich?

Lösung

Everything is perfectly OK. It's because QDataWidgetMapper sets data for all connected widgets, thus using toNext you set data from second row for all mapped widgets.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top