如何将mousePressEvent从QItemDelegate传递给QTableView

时间:2016-05-07 16:47:34

标签: python qt pyqt qtableview qitemdelegate

代码创建一个QTableView。左列预先填充了QLineEdits委托。右列未填充任何代理。

当点击左栏的委托QLineEdit时,被委派的项目会阻止'clicked'信号,并且tableView“cell”永远不会被选中。

要使tableView项被选中,mousePressEvent应该能够一直通过委托项到tableView。除了行0之外,未选择所有其他索引行。如何使它适用于所有模型索引?

enter image description here

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

class LineEdit(QTextEdit):
    def __init__(self, parent=None):
        super(LineEdit, self).__init__(parent)
    def mousePressEvent(self, event):
        tableView = self.parent().parent()
        tableView.mousePressEvent(event)

class Delegate(QItemDelegate):
    def createEditor(self, parent, option, index):
        return LineEdit(parent)

def onClick(index):
    print 'tableView.onClick:', index

tableView = QTableView()
tableView.setModel(QStandardItemModel(4, 2))
tableView.clicked.connect(onClick)
tableView.setItemDelegate(Delegate())

for row in range(4):
    tableView.openPersistentEditor(tableView.model().index(row, 0))

tableView.show()
app.exec_()

user1034749发布的解决方案:

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

class LineEdit(QTextEdit):
    def __init__(self, parent=None):
        super(LineEdit, self).__init__(parent)

    def mouseReleaseEvent(self, event):
        super(LineEdit, self).mouseReleaseEvent(event)
        table = self.parent().parent() # added by me here
        tableView.selectRow(0) # to fix the issue with tableView row not getting selected on delegated click.
        event.ignore()

    def mousePressEvent(self, event):
        super(LineEdit, self).mousePressEvent(event)
        event.ignore()

class Delegate(QItemDelegate):
    def createEditor(self, parent, option, index):
        return LineEdit(parent)

def onClick(index):
    print 'tableView.onClick:', index
    selectedIndexes = tableView.selectionModel().selectedRows()

tableView = QTableView()
tableView.setSelectionBehavior(QTableView.SelectRows)
tableView.setModel(QStandardItemModel(4, 2))
tableView.clicked.connect(onClick)
tableView.setItemDelegate(Delegate())

for row in range(4):
    tableView.openPersistentEditor(tableView.model().index(row, 0))

tableView.show()
app.exec_()

1 个答案:

答案 0 :(得分:2)

要通过事件,你需要忽略它,就像这样:

 def mouseReleaseEvent(self, event):
        print "mouse release"
        super(LineEdit, self).mouseReleaseEvent(event)
        event.ignore()

 def mousePressEvent(self, event):
        print "mouse press"
        super(LineEdit, self).mousePressEvent(event)
        event.ignore()