简体   繁体   English

使用整数创建项目,QStandardItem 不提供 QSpinBox

[英]Creating item with a integer, QStandardItem doesn't provide QSpinBox

I use PySide2 and QTableView with QStandardItemModel (object called resourcesModel) in my program.我在我的程序中将 PySide2 和 QTableView 与 QStandardItemModel(称为资源模型的对象)一起使用。 When I use the following code to create, fill and put an item into the table:当我使用以下代码创建、填充并将一个项目放入表中时:

item = QStandardItem()
item.setData(123123, Qt.EditRole)
resourcesModel.setItem(1, 1, item)

when I double-click on a cell containg that value, it provides a box to edit the data, that I can put letters into.当我双击包含该值的单元格时,它会提供一个编辑数据的框,我可以将字母放入其中。 My expected behaviour is to have a QSpinBox so that only numbers can be put there.我的预期行为是有一个 QSpinBox 以便只能将数字放在那里。

This code:这段代码:

item = QStandardItem()
item.setData(0.25, Qt.EditRole)
resourcesModel.setItem(1, 1, item)

presents a QDoubleSpinBox after double-clicking the cell, as expected.正如预期的那样,在双击单元格后显示一个 QDoubleSpinBox。 Both of these codes in PyQt5 provide the spinboxes as expected. PyQt5 中的这两个代码都按预期提供了旋转框。

Why does QStandardItem doesn't provide a QSpinBox, when the value put in is just an integer?当输入的值只是一个整数时,为什么 QStandardItem 不提供 QSpinBox? Is it possible to get around this without writing a custom delegate?是否可以在不编写自定义委托的情况下解决此问题?

Thank you for all your answers.感谢您的所有回答。

Explanation:解释:

What happens is that PySide2 converts the integer from python to LongLong (QVariant::LongLong=4) in C++ which is not handled by the default QItemEditorFactory by default making a QLineEdit used (in PyQt is converted to QMetaType::Int=2).发生的情况是 PySide2 在 C++ 中将整数从 python 转换为 LongLong (QVariant::LongLong=4),默认情况下,默认 QItemEditorFactory 不处理该整数,默认情况下使用QLineEdit (在 PyQt 中转换为 QMetaType::Int=2)。

Solution:解决方案:

One possible solution is to create a custom QItemEditorFactory that returns the appropriate widget:一种可能的解决方案是创建一个返回适当小部件的自定义 QItemEditorFactory :

from PySide2 import QtCore, QtGui, QtWidgets


class ItemEditorFactory(QtWidgets.QItemEditorFactory):
    def createEditor(self, userType, parent):
        if userType == 4:
            return QtWidgets.QSpinBox(parent, minimum=-2147483648, maximum=2147483647)
        return super().createEditor(userType, parent)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    factory = ItemEditorFactory() QtWidgets.QItemEditorFactory.setDefaultFactory(factory)

    w = QtWidgets.QTableView()

    resourcesModel = QtGui.QStandardItemModel(2, 2)
    w.setModel(resourcesModel)

    item = QtGui.QStandardItem()
    item.setData(123123, QtCore.Qt.EditRole)
    resourcesModel.setItem(1, 1, item)

    w.resize(640, 480)
    w.show()

    app.exec_()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM