QTableView:更改双精度值的精度

7
如果模型返回的是一个双精度浮点数,作为EditRole,则(据说)QTableView将使用QDoubleSpinBox作为编辑器。我该如何更改该控件中的精度?
4个回答

4

QTableView中QDoubleSpinBox的精度行为在这里有解释,因此要解决问题,您需要设置自己的QDoubleSpinBox,有两种方法可以根据Subclassing QStyledItemDelegate的结尾部分来实现:使用编辑器项目工厂或子类化QStyledItemDelegate。后一种方式需要您重新实现QStyledItemDelegate的四个方法,我觉得有点冗长,所以我选择了第一种方式,以下是PyQt中的示例代码:

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)

2

我一直没有找到一个好的方法来获取那些旋转框。 QTableView 的默认委托是 QStyledItemDelegate。在 Qt::EditRole 中创建项目时,它使用由默认的 QItemEditorFactory 类创建的项目,您可以使用 QItemEditorFactory::defaultFactory() 访问该类。然后,您可以在那里注册自己的编辑器,但我没有看到编辑已经存在的编辑器的好方法。

相反,最可能的做法是实现自己的委托,并指定不同的精度。有一个示例,使用 QSpinBox 制作委托,您可以将其替换为 QDoubleSpinBox。然后,在 createEditor 中,您将使用 setDecimals 来设置旋转框的精度。然后,您可以使用 setItemDelegate 将该委托应用于您的表格。


关于使用编辑器项工厂来解决问题(我认为这有点整洁!),请参见我的答案 https://dev59.com/SYrda4cB1Zd3GeqPJ0Ll#51763156 - iMath

0
这是一个最简单的QStyledItemDelegate实现,用于修改QDoubleSpinBox的精度。
const int DOUBLESP_PRECISION = 6;

class SpinBoxDelegate : public QStyledItemDelegate
{
public:
    QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const Q_DECL_OVERRIDE
        {
            auto w = QStyledItemDelegate::createEditor(
                parent, option, index);

            auto sp = qobject_cast<QDoubleSpinBox*>(w);
            if (sp)
            {
                sp->setDecimals(DOUBLESP_PRECISION);
            }
            return w;
        }
};

使用子类化 QStyledItemDelegate 的方式需要根据 Subclassing QStyledItemDelegate 的结尾部分重新实现 QStyledItemDelegate 的四个方法。 - iMath
@iMath 不需要实现所有的方法。 - eyllanesc
@iMath 上述代码已经测试并按预期工作。其他方法已经由 QStyledItemDelegate 实现,我只需要保持它们的行为不变即可。 - HeyYO

0

根据文档,可以通过调用decimals来更改QDoubleSpinBox的精度。


1
我认为您需要解释如何访问双精度旋转框编辑器以更改精度。 - vahancho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接