1

QTableView指定QAbstractTableModel为模型。并ItemDelegate(QItemDelegate)分配给tableView.openPersistentEditor. 现在,当单击 tableView 时,事件不会一直传播到 tableView (它是否被委托阻止QLineEditor)。

传递可用于完成任务的 mousePressEvent ItemDelegate QTableView 的模型 QItemInstance QItemDelegate` 标志的QLineEdit's方法event that is passed through theto什么when the tableView's item is clicked even while it is occupied by? Is there any

该代码创建了一个带有模型和委托的 tableView。通过单击第 0 列或第 1 列触发的事件不会传播到 tableView 的项目,因为该项目保持取消选中状态。

取消注释与tableView.setSelectionBehavior(QtGui.QTableView.SelectRows)修复问题的行。可以?

在此处输入图像描述

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class LineEdit(QtGui.QLineEdit):
    def __init__(self, parent=None, total=20):
        super(LineEdit, self).__init__(parent=parent)

    def mousePressEvent(self, event):
        print 'mousePressEvent', event
        super(LineEdit, self).mousePressEvent(event)

class Delegate(QtGui.QItemDelegate):
    def __init__(self):
        QtGui.QItemDelegate.__init__(self)

    def createEditor(self, parent, option, index):
        if index.column()==0:
            lineedit=LineEdit(parent)
            return lineedit

        elif index.column()==1:
            combo=QtGui.QComboBox(parent)
            return combo

    def setEditorData(self, editor, index):
        row = index.row()
        column = index.column()
        value = index.model().items[row][column]
        if isinstance(editor, QtGui.QComboBox):
            editor.addItems(['Somewhere','Over','The Rainbow'])
            editor.setCurrentIndex(index.row())
        if isinstance(editor, QtGui.QLineEdit):
            editor.setText('Somewhere over the rainbow')

class Model(QtCore.QAbstractTableModel):
    def __init__(self):
        QtCore.QAbstractTableModel.__init__(self)
        self.items = [[1, 'one', 'ONE'], [2, 'two', 'TWO'], [3, 'three', 'THREE']]

    def flags(self, index):
        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable
    def rowCount(self, parent=QtCore.QModelIndex()):
        return 3 
    def columnCount(self, parent=QtCore.QModelIndex()):
        return 3

    def data(self, index, role):
        if not index.isValid(): return 
        row = index.row()
        column = index.column()
        if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
            return self.items[row][column]

def tableViewClicked(index):
    print 'clicked:  %s'%index


tableModel=Model()
tableView=QtGui.QTableView() 
tableView.setModel(tableModel)
tableView.setItemDelegate(Delegate())
# tableView.setSelectionBehavior(QtGui.QTableView.SelectRows)
tableView.clicked.connect(tableViewClicked)

for row in range(tableModel.rowCount()):
    for column in range(tableModel.columnCount()):
        index=tableModel.index(row, column)
        tableView.openPersistentEditor(index)

tableView.show()
app.exec_()
4

1 回答 1

1

为什么不在委托项的函数中使用模型对象指针?例如,将您的委托项目的信号连接到模型的插槽,或者在您的委托项目的事件处理程序中调用模型的函数?

于 2016-05-04T02:29:17.107 回答