如何防止 QTableView 项在双击时被清除

How to prevent QTableView item from getting cleared on double-click

使用 QAbstractTableModel 的 flag() 方法将 QTableView 设置为可编辑:

def flags(self, index):
    return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable

双击 QTableView 的项目将此项目置于编辑模式。默认情况下,预先存在的字符串从字段中消失,整个项目为空白。我想知道是否可以避免或覆盖这种行为?

这是用户双击之前的QTableView字段:

这是双击时的样子:

已编辑的工作代码(非常感谢M4rtini):

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os

class Model(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.items =[ 
                    ['Row0_Column0','Row0_Column1','Row0_Column2'],
                    ['Row1_Column0','Row1_Column1','Row1_Column2'],
                    ['Row2_Column0','Row2_Column1','Row2_Column2']
                    ]

    def flags(self, index):
        return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable

    def rowCount(self, parent):
        return len(self.items)       
    def columnCount(self, parent):
        return 3

    def data(self, index, role):
        if not index.isValid(): return QVariant()
        row=index.row()
        column=index.column()

        if row>len(self.items): return QVariant()        
        if column>len(self.items[row]): return QVariant()

        if role == Qt.EditRole or role == Qt.DisplayRole:
            return QVariant(self.items[row][column])

        return QVariant()

    def setData(self, index, value, role=Qt.EditRole):
        if index.isValid():            
            if role == Qt.EditRole:
                row = index.row()
                column=index.column()
                if row>len(self.items) or column>len(self.items[row]):
                    return False
                else:
                    self.items[row][column]=value  
                    return True
        return False

class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        tablemodel=Model(self)               
        tableview=QTableView(self) 
        tableview.setModel(tablemodel)    
        layout=QVBoxLayout(self)
        layout.addWidget(tableview)
        self.setLayout(layout)      

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

使用 EditRole 调用时需要设置数据的 return 值:

def data(self, index, role):
    if not index.isValid(): return false
    row=index.row()
    if row>len(self.items): return false

    if role == Qt.DisplayRole or role == Qt.EditRole:
        return self.items[row]