iGwok
iGwok

Reputation: 333

How to modify the value from a QDataWidgetMapper

So I'm using a QDataWidgetMapper to map values from a QSqlQueryModel to widgets in my interface. This is working nicely, and each time my Model is updated or refreshed the widgets are updated too... Great!

But let's say that I have a QLabel... and this QLabel has been mapped to a field in the Model called 'City', and the text displayed by the QLabel in showing 'LONDON'. Is there a way to format this text so that it's displayed as 'London' instead? whilst also maintaining the mapping relationship, and without changing the database that the QSqlQueryModel is querying?

Thanks!

EDIT - Here's an simplified example of the code I have so far:

import sys
from PyQt4 import QtCore, QtGui


class DemoModel(QtCore.QAbstractTableModel):
    def __init__(self):
        super(DemoModel, self).__init__()
        self.visibleColumns = ['city', 'country']
        self.items = [
            {'city': 'LONDON', 'country': 'England'},
            {'city': 'GLASGOW', 'country': 'Scotland'},
            {'city': 'CARDIF', 'country': 'Wales'},
            ]


    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.items)


    def columnCount(self, parent=QtCore.QModelIndex()):
        return len(self.visibleColumns)


    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.ToolTipRole:
            colName = self.visibleColumns[index.column()]
            return self.items[index.row()].get(colName, '')


    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.DisplayRole and orientation == QtCore.Qt.Horizontal:
            return self.visibleColumns[section]



class TestWindow(QtGui.QWidget):
    def __init__(self):
        super(TestWindow, self).__init__()
        self.resize(100, 100)
        layout = QtGui.QVBoxLayout(self)

        demoLabel = QtGui.QLabel()
        layout.addWidget(demoLabel)
        mapper.addMapping(demoLabel, 0, "text")



model = DemoModel()
mapper = QtGui.QDataWidgetMapper()
mapper.setModel(model)

app = QtGui.QApplication(sys.argv)
demo =  TestWindow()
demo.show()
sys.exit(app.exec_())

Upvotes: 1

Views: 980

Answers (1)

ekhumoro
ekhumoro

Reputation: 120578

You should set an item delegate on the data mapper, and re-implement the setEditorData method:

class ItemDelegate(QtGui.QItemDelegate):
    def setEditorData(self, editor, index):
        editor.setText(index.data().title())

mapper = QtGui.QDataWidgetMapper()
mapper.setModel(model)
delegate = ItemDelegate()
mapper.setItemDelegate(delegate)

For this to work properly, the mappings must be made without specifying the property name:

mapper.addMapping(demoLabel, 0)

(Note that for editable display widgets, you might also need to re-implement the setModelData method).

Upvotes: 1

Related Questions