QTreeView / QStandardItemModel中的选定行

时间:2014-09-14 19:25:07

标签: python pyqt4

我正在尝试使用QTreeView和QStandardItemModel在PyQt4中实现帐户结构(带子帐户)。经过大量的试验和错误后,我终于准备了树视图。现在,当我单击树视图中的特定行时,我想要发生一些事情。我从GTK工具包中获得的经验表明,当单击一行时,我会听到发出的某种信号,然后写一个信号处理程序来找出被点击的行。我无法弄清楚如何在PyQt中做到这一点。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

课程QtGui.QTreeView中有信号void clicked (const QModelIndex&)& void pressed (const QModelIndex&)可供使用。此信号函数位于QtGui.QAbstractItemViewQtGui.QTreeView继承。

此信号中的数据为QtCore.QModelIndex类,因此此类QAbstractItemModel QModelIndex.model (self)可以获取您的模型数据QtGui.QStandardItemModel

实施例

import sys
from PyQt4 import QtGui

class QCustomTreeView (QtGui.QTreeView):
    def __init__ (self, parentQWidget = None):
        super(QCustomTreeView, self).__init__(parentQWidget)
        self.pressed.connect(self.myPressedEvent)

    def myPressedEvent (self, currentQModelIndex):
        # Use QModelIndex to show current data pressed
        print currentQModelIndex.column(), currentQModelIndex.row()
        print currentQModelIndex.data().toString()
        # Also can implement your QStandardItemModel here
        currentQStandardItemModel = currentQModelIndex.model()

myQApplication = QtGui.QApplication([])
myQTreeView = QCustomTreeView()
headerQStandardItemModel = QtGui.QStandardItemModel()
headerQStandardItemModel.setHorizontalHeaderLabels([''] * 4)
myQTreeView.setModel(headerQStandardItemModel)
# Append data row 1
row1QStandardItem = QtGui.QStandardItem('ROW 1')
row1QStandardItem.appendRow([QtGui.QStandardItem(''), QtGui.QStandardItem('1'), QtGui.QStandardItem('3'), QtGui.QStandardItem('5')])
headerQStandardItemModel.appendRow(row1QStandardItem)
# Append data row 2
row2QStandardItem = QtGui.QStandardItem('ROW 2')
row2QStandardItem.appendRow([QtGui.QStandardItem(''), QtGui.QStandardItem('2'), QtGui.QStandardItem('4'), QtGui.QStandardItem('6')])
headerQStandardItemModel.appendRow(row2QStandardItem)
myQTreeView.show()
sys.exit(myQApplication.exec_())