我将用一个小例子来演示我的问题:
import sys
from PySide import QtCore, QtGui
class TaskModel(QtCore.QAbstractTableModel):
def __init__(self, tasks=[[" ", " ", " ", " "]]):
# def __init__(self, tasks=[[]]):
super().__init__()
self.__tasks = tasks
self.__headers = ["Folder", "Command", "Patterns", "Active", "Recursive"]
def rowCount(self, *args, **kwargs):
return len(self.__tasks)
def columnCount(self, *args, **kwargs):
coln = len(self.__tasks[0])
return coln
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self.__headers[section]
else:
# set row names: color 0, color 1, ...
return "%s" % str(section+1)
def data(self, index, role):
row = index.row()
col = index.column()
value = self.__tasks[row][col]
# text content
if role == QtCore.Qt.DisplayRole:
return value
def insertRows(self, position, rows, parent=QtCore.QModelIndex()):
self.beginInsertRows(parent, position, position + rows - 1)
row = ["a", "b", "c", "d"]
for i in range(rows):
self.__tasks.insert(position, row)
self.endInsertRows()
return True
class Mc(QtGui.QWidget):
def __init__(self):
super().__init__()
self.tab = QtGui.QTableView()
self.model = TaskModel()
self.tab.setModel(self.model)
self.addbtn = QtGui.QPushButton("Add")
self.addbtn.clicked.connect(self.insert)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.tab)
layout.addWidget(self.addbtn)
self.setLayout(layout)
def insert(self):
self.model.insertRow(0)
app = QtGui.QApplication(sys.argv)
mc = Mc()
mc.show()
sys.exit(app.exec_())
请注意,我__init__
对 TaskModel 类有两行函数,第一行给出 [[" ", " ", " ", " "]] 作为 __task 的默认数据集,第二行给出 [[]]。
第一个工作正常:
除了有一个不需要的行坐在底部。
第二个__init__
函数在尝试删除不需要的行时,使用 [[]] 作为默认数据集,但结果是灾难性的:
如何删除不需要的底行,同时仍使其正常工作(使用标题和所有内容)?