If a double value returned as EditRole by a model, then (supposedly) QDoubleSpinBox is used by QTableView as an editor. How can I change precision in that control?
The precision behavior of QDoubleSpinBox in a QTableView is explained here , so to solve the problem , you need to set your own QDoubleSpinBox, there are two ways to do this according to the end part of Subclassing QStyledItemDelegate: using an editor item factory or subclassing QStyledItemDelegate. The latter way requires you to reimplement four methods of QStyledItemDelegate, I just fount it a bit lengthy, so I choose the first way , sample code in PyQt following :
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class ItemEditorFactory(QItemEditorFactory): # http://doc.qt.io/qt-5/qstyleditemdelegate.html#subclassing-qstyleditemdelegate It is possible for a custom delegate to provide editors without the use of an editor item factory. In this case, the following virtual functions must be reimplemented:
def __init__(self):
super().__init__()
def createEditor(self, userType, parent):
if userType == QVariant.Double:
doubleSpinBox = QDoubleSpinBox(parent)
doubleSpinBox.setDecimals(3)
doubleSpinBox.setMaximum(1000) # The default maximum value is 99.99.所以要设置一下
return doubleSpinBox
else:
return super().createEditor(userType, parent)
styledItemDelegate=QStyledItemDelegate()
styledItemDelegate.setItemEditorFactory(ItemEditorFactory())
self.tableView.setItemDelegate(styledItemDelegate)
self.tableView.setModel(self.sqlTableModel)
I have not been able to find a good way to get at those spin boxes. The default delegate for a QTableView
is a QStyledItemDelegate. When creating a item in Qt::EditRole
it uses items created by the default QItemEditorFactory class, which you can access using QItemEditorFactory::defaultFactory()
. You could then register your own editor there, however I do not see a good way to edit the ones that are already there.
Instead most likely what you should do is implement your own delegate with a different precision specified. There is a example to make a delegate using a QSpinBox
, which you would replace with a QDoubleSpinBox
. Then in createEditor
you would then use setDecimals
to set the spin box to the precision that you want. You then apply that delegate to your table with setItemDelegate
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With