Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTableView: change precision for double values

Tags:

qt

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?

like image 939
pashazz Avatar asked Apr 28 '15 21:04

pashazz


2 Answers

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)
like image 180
iMath Avatar answered Nov 12 '22 06:11

iMath


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.

like image 40
Chris Avatar answered Nov 12 '22 07:11

Chris