代码:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class StringListModel(QAbstractListModel):
def __init__(self, stringList, parent=None):
super(StringListModel, self).__init__(parent)
self.stringList = stringList
# int rowCount(const QModelIndex &parent = QModelIndex()) const;
# QVariant data(const QModelIndex &index, int role) const;
# QVariant headerData(int section, Qt::Orientation orientation,
# int role = Qt::DisplayRole) const;
def rowCount(self,parent=QModelIndex()):
return len(self.stringList)
def data(self,index,role= Qt.DisplayRole):
if (not index.isValid()):
return QVariant()
if (index.row() >= len(self.stringList)):
return QVariant()
if (role == Qt.DisplayRole):
return self.stringList[index.row()]
else:
return QVariant()
def headerData(self, section, orientation, role= Qt.DisplayRole):
if (role != Qt.DisplayRole):
return QVariant()
# print(type(section))
# print(section)
if (orientation == Qt.Horizontal):
return "Column %d" % (section)
else:
return "Row %d" % (section)
if __name__ == "__main__":
app = QApplication(sys.argv)
qlist = list()
qlist.append("a")
qlist.append("b")
qlist.append("c")
qlist.append("abcd")
model = StringListModel(qlist)
qlistView = QListView()
qlistView.setModel(model)
qlistView.show()
tableView = QTableView()
tableView.setModel(model)
tableView.show()
app.exec_()
效果:
不可编辑