QTableView:无法输入小数

QTableView: Cannot Enter Decimals

我用一些数据初始化我的 tables,单元格是 editable。数据访问和写入由模型处理。 如果单元格中的现有数据是整数,QTableView 似乎不允许我输入小数(甚至不能输入点作为小数点分隔符)。如果现有数据是小数,那我可以输入小数。

如何设置 table 以便我可以随时 输入小数,即使现有值为整数

有关此类 table 的示例,请参见下面的脚本。

import typing
from sys import argv
from PyQt5.QtWidgets import QTableView, QApplication, QVBoxLayout, QFrame
from PyQt5.Qt import QAbstractTableModel, QModelIndex, Qt


app = QApplication(argv)
base = QFrame()
layout = QVBoxLayout(base)
base.setLayout(layout)

table = QTableView(base)
layout.addWidget(table)

data = [[10, 100],
        [20.5, 200]]


class Model(QAbstractTableModel):

    def columnCount(self, parent: QModelIndex = ...) -> int:
        return 2

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return 2

    def flags(self, index: QModelIndex) -> Qt.ItemFlags:
        return Qt.ItemIsEnabled | Qt.ItemIsEditable

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        return data[index.row()][index.column()]

    def setData(self, index: QModelIndex, value: typing.Any, role: int = ...) -> bool:
        data[index.row()][index.column()] = float(value)
        return True


model = Model()
table.setModel(model)

base.show()
exit(app.exec_())

只需在 int 值后添加 ".0" 以 float 类型的值初始化数据变量即可:

data = [[10.0, 100.0], [20.5, 200.0]]

这里是你想要的最终代码:

import typing
from sys import argv
from PyQt5.QtWidgets import QTableView, QApplication, QVBoxLayout, QFrame
from PyQt5.QtCore import QAbstractTableModel, QModelIndex, Qt


app = QApplication(argv)
base = QFrame()
layout = QVBoxLayout(base)
base.setLayout(layout)

table = QTableView(base)
layout.addWidget(table)

data = [[10.0, 100.0],
        [20.5, 200.0]]


class Model(QAbstractTableModel):

    def columnCount(self, parent: QModelIndex = ...) -> int:
        return 2

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return 2

    def flags(self, index: QModelIndex) -> Qt.ItemFlags:
        return Qt.ItemIsEnabled | Qt.ItemIsEditable

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        return data[index.row()][index.column()]

    def setData(self, index: QModelIndex, value: typing.Any, role: int = ...) -> bool:
        data[index.row()][index.column()] = float(value)
        return True


model = Model()
table.setModel(model)

base.show()
exit(app.exec_())