Python 如何检查PyQt TableModelView中传递的值是否为整数,而不是例如字母/符号?
我对Python比较陌生,尤其是PyQt和模型视图编程。我希望有人能够在我的表格中只输入整数,而不是字母/符号等。以下是我为tableView小部件制作的模型:Python 如何检查PyQt TableModelView中传递的值是否为整数,而不是例如字母/符号?,python,pyqt,Python,Pyqt,我对Python比较陌生,尤其是PyQt和模型视图编程。我希望有人能够在我的表格中只输入整数,而不是字母/符号等。以下是我为tableView小部件制作的模型: class PixelTableModel(QtCore.QAbstractTableModel): def __init__(self): super(PixelTableModel, self).__init__() self.pixel_coordinate = [[None, None,
class PixelTableModel(QtCore.QAbstractTableModel):
def __init__(self):
super(PixelTableModel, self).__init__()
self.pixel_coordinate = [[None, None, None, None]]
def rowCount(self, parent):
return 1
def columnCount(self, parent):
return 4
def flags(self, index):
return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def setData(self, index, value, role = QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
self.pixel_coordinate[row][column] = value
print(self.pixel_coordinate) #testing
return True
return False
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
row = index.row()
column = index.column()
value = self.pixel_coordinate[row][column]
return value
def headerData(self, section, orientation, role): # section = row column, orientation = vertical/horizontal
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
dict = {0: "Xstart", 1: "Ystart", 2: "Xmax", 3: "Ymax"}
for key in dict:
if section == key:
return dict[key]
else:
return "Pixel coordinate"
它似乎可以工作,但显然对于仍可以在tableView中输入字母/符号的部分除外。我在setData()方法中尝试了一些方法,但似乎无法使其工作,总是出现某种类型的错误,或者它甚至根本不会更改框。谢谢所有能帮我的人。也为糟糕的英语感到抱歉。对于仍然感兴趣的人,在再次阅读后,使用简单的“尝试除块”修复它:
def setData(self, index, value, role = QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
try:
row = index.row()
column = index.column()
string_to_int = int(value)
self.pixel_coordinate[row][column] = value
print(self.pixel_coordinate) #testing
return True
except ValueError:
print("Not a number")
return False
return False