QDataWidgetMapper: wrong mapping

删除回忆录丶 提交于 2019-12-11 05:47:52

问题


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_())

回答1:


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.



来源:https://stackoverflow.com/questions/23352045/qdatawidgetmapper-wrong-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!