TableView 不可编辑
TableView not editable
为什么这段代码中的 TableView 是不可编辑的。我尝试将 editTriggers 设置为 AllEditTriggers 值,但没有成功:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def data(self, index, role):
if role == Qt.DisplayRole:
return self._data[index.row()][index.column()]
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return len(self._data[0])
app = QtWidgets.QApplication(sys.argv)
table = QtWidgets.QTableView()
table.move(200,200)
table.setFixedSize(500,300)
data = [
[3, 5, 2],
[1, 0, 0],
[3, 8, 0],
[3, 3, 2],
[7, 8, 9],
]
model = TableModel(data)
table.setModel(model)
table.show()
app.exec_()
默认模型不可编辑,要使其可编辑,您必须在 flags()
方法中添加 Qt::ItemIsEditable
标志,此外还要实现实现改变。
class TableModel(QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def rowCount(self, parent=QModelIndex()):
return len(self._data)
def columnCount(self, parent=QModelIndex()):
return len(self._data[0])
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
return self._data[index.row()][index.column()]
def setData(self, index, value, role=Qt.EditRole):
if role in (Qt.DisplayRole, Qt.EditRole):
self._data[index.row()][index.column()] = value
self.dataChanged.emit(index, index)
return True
def flags(self, index):
return super().flags(index) | Qt.ItemIsEditable
为什么这段代码中的 TableView 是不可编辑的。我尝试将 editTriggers 设置为 AllEditTriggers 值,但没有成功:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def data(self, index, role):
if role == Qt.DisplayRole:
return self._data[index.row()][index.column()]
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return len(self._data[0])
app = QtWidgets.QApplication(sys.argv)
table = QtWidgets.QTableView()
table.move(200,200)
table.setFixedSize(500,300)
data = [
[3, 5, 2],
[1, 0, 0],
[3, 8, 0],
[3, 3, 2],
[7, 8, 9],
]
model = TableModel(data)
table.setModel(model)
table.show()
app.exec_()
默认模型不可编辑,要使其可编辑,您必须在 flags()
方法中添加 Qt::ItemIsEditable
标志,此外还要实现实现改变。
class TableModel(QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def rowCount(self, parent=QModelIndex()):
return len(self._data)
def columnCount(self, parent=QModelIndex()):
return len(self._data[0])
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
return self._data[index.row()][index.column()]
def setData(self, index, value, role=Qt.EditRole):
if role in (Qt.DisplayRole, Qt.EditRole):
self._data[index.row()][index.column()] = value
self.dataChanged.emit(index, index)
return True
def flags(self, index):
return super().flags(index) | Qt.ItemIsEditable