Reputation: 1173
I am to learn model/view and write a demo, but my table has no data and couldn't set data.
And checkIndex
method of QAbstractItemMode
couldn't work ???
The code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtPrintSupport import *
from PyQt5.QtChart import *
import numpy as np
class TableModel(QAbstractTableModel):
def __init__(self, data: np.ndarray):
super().__init__()
self.dataArray = data
def rowCount(self, parent):
return self.dataArray.shape[0]
def columnCount(self, parent):
return self.dataArray.shape[1]
def data(self, index: QModelIndex, role=None):
# checkIndex method not working ???
# self.checkIndex(index, QAbstractItemModel::IndexIsValid)
if not index.isValid():
return None
if index.row() >= self.dataArray.shape[0] or index.column() >= self.dataArray.shape[1]:
return None
if role in [Qt.DisplayRole, Qt.EditRole]:
return self.dataArray[index.row()][index.column()]
else:
return None
def headerData(self, section, orientation, role=None):
if role != Qt.DisplayRole:
return None
if orientation == Qt.Horizontal:
return f'Column {section}'
else:
return f'Row {section}'
def flags(self, index: QModelIndex):
if not index.isValid():
return Qt.ItemIsEnabled
return super().flags(index) | Qt.ItemIsEditable
def setData(self, index: QModelIndex, value, role=None):
if index.isValid() and role == Qt.EditRole:
self.dataArray[index.row()][index.column()] = value
self.dataChanged.emit(index, index, [role])
return True
return False
class DemoA(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
data = np.random.randint(1, 100, (4, 6))
model = TableModel(data)
# delegate = ComboBoxDelegate()
table = QTableView()
table.setModel(model)
# table.setItemDelegate(delegate)
self.setCentralWidget(table)
app = QApplication([])
demo = DemoA()
demo.show()
app.exec()
The result:
Upvotes: 0
Views: 261
Reputation: 244162
PyQt5 does not handle numpy data types so it will not display them. In your case, the data stored in the numpy array is numpy.int64, so the solution is to convert it to an integer or float:
if role in [Qt.DisplayRole, Qt.EditRole]:
return int(self.dataArray[index.row()][index.column()])
Upvotes: 1