尝试使用QStandardItemModel将行插入QTableView中。
from PyQt5.QtCore import Qt, QSortFilterProxyModel, QModelIndex, QSize
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtWidgets import QWidget, QTableView, QPushButton, QVBoxLayout, QAbstractItemView
class SclDataBrowse(QWidget):
def __init__(self, parent=None):
super(SclDataBrowse, self).__init__(parent)
self.resize(336, 462)
self.layout = QVBoxLayout(self)
self.view = QTableView(self)
self.btn_New = QPushButton(self)
self.btn_New.setMinimumSize(QSize(70, 21))
self.btn_New.setMaximumSize(QSize(70, 21))
self.btn_New.setText('New')
self.layout.addWidget(self.view)
self.layout.addWidget(self.btn_New)
self.model = QStandardItemModel()
self.proxy = QSortFilterProxyModel()
self.setup_ui()
self.setup_connections()
def setup_ui(self):
self.model.setColumnCount(4)
self.model.setHorizontalHeaderLabels(["Record ID", "Starting Receipts", "Ending Receipts", "Billing Rate"])
self.proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
self.proxy.setSourceModel(self.model)
self.view.setModel(self.proxy)
self.view.verticalHeader().setVisible(False)
self.view.verticalHeader().setDefaultSectionSize(22)
self.view.setEditTriggers(QAbstractItemView.AllEditTriggers)
def setup_connections(self):
self.btn_New.clicked.connect(self.add_record)
def add_record(self):
row = self.model.rowCount()
self.model.insertRow(row)
ndx = self.model.index(row, 1, QModelIndex())
self.view.edit(ndx)
无法使表格进入编辑模式,并且出现错误:
edit: index was invalid
edit editing failed
请解释我做错了什么。
答案 0 :(得分:1)
引起问题的原因是ndx属于QStandardItemModel
,但是编辑需要QModelIndex
属于视图中建立的模型,并且该模型是QSortFilterProxyModel
,因此您拥有将属于源的QModelIndex
转换为与QModelIndex
代理对应的mapFromSource()
:
def add_record(self):
row = self.model.rowCount()
self.model.insertRow(row)
ndx = self.model.index(row, 1)
ix = self.proxy.mapFromSource(ndx)
self.view.edit(ix)