Home > Mobile >  QTableView: Cannot Enter Decimals
QTableView: Cannot Enter Decimals

Time:06-05

I initialize my tables with some data, and the cells are editable. Data access and writing is handled by a model. If the existing data in a cell is an integer, it appears that QTableView does not let me enter a decimal number (cannot even type a dot as a decimal separator). If the existing data is a decimal, then I can enter a decimal.

How can I set up the table so that I can enter a decimal at all times, even when the existing value is an integer?

See below script for an example of such a 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_())

CodePudding user response:

Just initialize data variable with values of float type by adding ".0" after int values to be:

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

here the final code that you want:

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_())
  • Related