I have got a QSqlTableModel with decimal numbers in one column. How can I format this column to have numbers with 4 decimal places (e.g.: 2,3 --> 2,3000; 4,567891 --> 4,5679). I am using pyqt5.
Edit:
I tried to subclass QSqlTableModel like this:
class AlignmentTable(QSqlTableModel):
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole and index.column() == 4:
value = '{:01.4f}'.format(self.data(index))
return value
But I get the error: RecursionError: maximum recursion depth exceeded in comparison
- Edit:
First I load the model like this:
def load_sitesizes(self):
self.mod_site_sizes = AlignmentTable(parent=None, db=dbtools.ProjectDB.use_project_db(self))
self.mod_site_sizes.setTable("vSiteSizes")
site_id = str(self.item_id)
self.mod_site_sizes.setFilter("SiteKey='"+site_id+"'")
self.mod_site_sizes.select()
self.mod_site_sizes.setEditStrategy(QSqlTableModel.OnFieldChange)
self.tblSiteSizes.setModel(self.mod_site_sizes)
and than your code in a subclass:
class AlignmentTable(QSqlTableModel):
def data(self, item, role):
if role == Qt.DisplayRole:
if item.column() == 4:
val = QSqlTableModel.data(self, item, Qt.DisplayRole)
if not isinstance(val, float):
val = float(val)
return '{:.4f}'.format(round(val, 4))