Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[QSqlTableModel] How to present NULL fields in ahuman friendly way?



  • I've got a model linked to a database table

    def _createModel(table):
            """Create and set up the model."""
            tableModel = QSqlRelationalTableModel()
            tableModel.setTable(table)
            tableModel.setEditStrategy(QSqlRelationalTableModel.OnFieldChange)
            tableModel.setRelation(1, QSqlRelation('clients', 'id', 'name'))
            tableModel.select()
            headers = ("ID", "Client", "Number", "Job", "Draft date", "Confirm date", "Job date", "Delivery date", "Notes")
            for columnIndex, header in enumerate(headers):
                tableModel.setHeaderData(columnIndex, Qt.Horizontal, header)
            return tableModel
    

    Then I show the data inside a QTableView

    self.ui.tbl_result.setModel(self.lapidiModel.model)
    self.ui.tbl_result.setSelectionBehavior(QAbstractItemView.SelectRows)
    self.ui.tbl_result.resizeColumnsToContents()
    

    Some of the dates fields can be NULL before that the job is finished and I see NULL on the presented table.
    How can I substitute those NULL with a string link "Not available" or something else when showing the table?



  • @Alhazred said in [QSqlTableModel] How to present NULL fields in ahuman friendly way?:

    How can I substitute those NULL with a string link "Not available" or something else when showing the table?

    The lazy way to do it (or test your idea) is to (subclass and) have data() return "Not available" string for Qt::DisplayRole when value for NULL.

    The correct way is to create a QStyledItemDelegate and use QStyledItemDelegate::displayText() for your string on NULL. The problem is --- and I remember finding this --- it says:

    This function is not called for empty model indices, i.e., indices for which the model returns an invalid QVariant.

    I can't recall how I handled this, and I don't know how the existing behaviour of "and I see NULL on the presented table." is implemented... Try it, else how about using the lazy way? :)

    P.S.

    and I see NULL on the presented table.

    You sure about this? I would have thought it would show as blank? Does it show same on a plain QSqlTableModel?



  • @JonB said in [QSqlTableModel] How to present NULL fields in ahuman friendly way?:

    You sure about this? I would have thought it would show as blank? Does it show same on a plain QSqlTableModel?

    You are right, I did know how the fields were declared and they could store NULL values, but I didn't check the actual content, those NULL printed on the table were strings, changing them to NULL, the fields appear empty.
    Now I will see how to use the delegates, thank you.


Log in to reply