2016-05-04 78 views
1

QTableView被指定爲QAbstractTableModel作爲模型。並且ItemDelegate(QItemDelegate)被分配了tableView.openPersistentEditor。現在,當單擊tableView時,事件不會一直傳播到tableView(它是否被代理QLineEditor阻止)。如何阻止項目委託阻止mousePressEvent

什麼會通過,可以用來把事情做好QLineEdit's mousePressEvent event that is passed through the ItemDelegate to QTableView中的模式when the tableView's item is clicked even while it is occupied by QItemInstance ? Is there any QItemDelegate`標誌的方法嗎?

該代碼使用模型和委託創建單個tableView。 單擊列0或列1觸發的事件不會傳播到tableView的項目,因爲項目保持取消選中狀態。

取消註釋tableView.setSelectionBehavior(QtGui.QTableView.SelectRows)可以解決該問題。可以?

enter image description here

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_() 

回答

1

爲什麼不能在您的代理項目的功能使用的模型對象的指針?例如,將委託項目的信號連接到模型的插槽,或者在委託項目的事件處理程序中調用模型的功能?

+0

在代理項目的事件處理程序中調用模型的函數將會起作用。有些人不會喜歡這樣的解決方案。 – alphanumeric