帮同事实现一个在表格的输入过程中,敲入回车后自动进入下一单元格编辑状态的需求。在setData中发送信号并将下一单元格的坐标进行传递。代码如下:
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTableView)
from PyQt5.QtCore import (QAbstractTableModel, QModelIndex, Qt, QVariant, pyqtSignal)
class MyModel(QAbstractTableModel):
editNext = pyqtSignal(QModelIndex)
m_gridData = [([''] * 3) for i in range(2)]
def __init__(self, parent=None):
super(MyModel,self).__init__(parent)
def rowCount(self, parent=QModelIndex()):
return 2
def columnCount(self, parent=QModelIndex()):
return 3
def data(self, index, role):
if role == Qt.DisplayRole:
return self.m_gridData[index.row()][index.column()]
return QVariant()
def setData(self, index, value, role):
if role == Qt.EditRole:
self.m_gridData[index.row()][index.column()] = value
tmp = index.sibling(index.row(), index.column()+1)
if tmp.isValid():
self.editNext.emit(tmp)
return True
def flags(self, index):
return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
tableView = QTableView()
self.setCentralWidget(tableView)
myModel = MyModel()
tableView.setModel(myModel)
# https://stackoverflow.com/questions/20267176/qtableviewedit-const-qmodelindex-index-failed
myModel.editNext.connect(tableView.edit, Qt.QueuedConnection)
if __name__ == '__main__':
a = QApplication(sys.argv)
w = MainWindow()
w.show()
a.exec_()