如何对PyQt4 QTreeWidget中的单击作出反应

时间:2013-07-03 12:13:00

标签: python pyqt4 qtreewidget

我是Pyhthon和Qt的新手,因此这个基本问题。我想要的是当我点击QTreeWidget中的一个项目时,会调用一个事件处理程序,告诉我哪个项目已被点击。我试过的代码是:

    self.dir_tree = QTreeWidget ()
    self.dir_tree.setColumnCount (3)
    self.dir_tree.setHeaderLabels (("File", "Type", "Size"))
    self.dir_tree.connect (dir_tree, SIGNAL ("itemClicked (QTreeWidgetItem*, int)"), self.onClickItem)

def onClickItem (self, column):
    print (column) 

这不运行,错误代码为:

TypeError: arguments did not match any overloaded call:
  QObject.connect(QObject, SIGNAL(), QObject, SLOT(),Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'function'
  QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'function'
  QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'function'

我做错了什么?还有一个与此相关的问题:如何确定点击了哪个项目?

我找不到这方面的教程,欢迎提出任何建议。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

问题太早了,经过大量的实验后我找到了答案。代码是错误的,没有提到self.dirtree和从self.dir_tree而不是self连接。所以正确的代码应该是:

    self.connect (self.dir_tree, SIGNAL ("itemClicked(QTreeWidgetItem*, int)"), self.onClickItem)

一些实验导致了以下回调:

def onClickItem (self, item, column):
    print (item, column) 

Item指的是单击的QTreeWidgetItem本身(在我的例子中,它是一个带有额外信息的派生类:仍然可以正常工作)和列到单击列。

最后一个问题仍然存在。我还没有很好地掌握信号/插槽。欢迎任何指向好教程的指针。