我是 PyQt 的新手。
我试图将 QTableView 放入一个类中,这样我就可以在类中定义它的行为,而无需将其与所有其他代码混合,但是当我这样做时,它就不会显示。
这是我正在学习的代码。这是借来的[使用 QAbstractTableModel 在 pyqt 中编辑表]。稍微重新调整它以与 Qt5 一起使用,并将 QTableView 移动到一个类中
import sys
from PyQt5 import QtGui, QtCore
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QVBoxLayout, QTableView, QWidget
from PyQt5.QtCore import *
# données à représenter
my_array = [['00','01','02'],
['10','11','12'],
['20','21','22']]
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
# création de la vue et du conteneur
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
tablemodel = MyTableModel(my_array, self)
table = Table(tablemodel)
layout = QVBoxLayout(self)
layout.addWidget(table)
self.setLayout(layout)
# création du modèle
class Table(QWidget):
def __init__(self, model):
super().__init__()
self.model = model
self.initUI()
def initUI(self):
self.setMinimumSize(300,300)
self.view = QTableView()
self.view.setModel(self.model)
class MyTableModel(QAbstractTableModel):
def __init__(self, datain, parent = None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.arraydata = datain
def rowCount(self, parent):
return len(self.arraydata)
def columnCount(self, parent):
return len(self.arraydata[0])
def data(self, index, role):
if not index.isValid():
return None
elif role != Qt.DisplayRole:
return None
return (self.arraydata[index.row()][index.column()])
"""
def setData(self, index, value):
self.arraydata[index.row()][index.column()] = value
return True
def flags(self, index):
return Qt.ItemIsEditable
"""
if __name__ == "__main__":
main()
如果我删除该类并使用
table = QTableView()
table.setModel(tablemodel)
表显示没有问题。
我缺少什么?