为什么我的表内容为空白并且无法设置数据?

问题描述 投票:0回答:1

我要学习model/view并编写一个演示,但是我的表没有日期,无法设置数据。并且checkIndexQAbstractItemMode方法无效???

代码:

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()

结果:

“”

python pyqt pyqt5
1个回答
0
投票

PyQt5不处理numpy数据类型,因此将不会显示它们。在您的情况下,存储在numpy数组中的数据是numpy.int64,因此解决方案是将其转换为整数或浮点数:

if role in [Qt.DisplayRole, Qt.EditRole]:
    return int(self.dataArray[index.row()][index.column()])
© www.soinside.com 2019 - 2024. All rights reserved.