PyQt:事件未触发,我的代码有什么问题? [英] PyQt: event is not triggered, what's wrong with my code?

查看:68
本文介绍了PyQt:事件未触发,我的代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我正在尝试编写一个简单的应用程序,它带有一个事件处理程序,当单击自定义 QTreeWidget 中的项目时,该事件处理程序会被激活.由于某种原因,它不起作用.由于我只是在学习它的开始,我无法弄清楚我做错了什么.代码如下:

I'm a Python newbie and I'm trying to write a trivial app with an event handler that gets activated when an item in a custom QTreeWidget is clicked. For some reason it doesn't work. Since I'm only at the beginning of learning it, I can't figure out what I'm doing wrong. Here is the code:

#!/usr/bin/env python

import sys

from PyQt4.QtCore import SIGNAL

from PyQt4.QtGui import QApplication
from PyQt4.QtGui import QMainWindow
from PyQt4.QtGui import QTreeWidget
from PyQt4.QtGui import QTreeWidgetItem

class MyTreeItem(QTreeWidgetItem):

    def __init__(self, s, parent = None):

        super(MyTreeItem, self).__init__(parent, [s])

class MyTree(QTreeWidget):

    def __init__(self, parent = None):

        super(MyTree, self).__init__(parent)
        self.setMinimumWidth(200)
        self.setMinimumHeight(200)
        for s in ['foo', 'bar']:
            MyTreeItem(s, self)
        self.connect(self, SIGNAL('itemClicked(QTreeWidgetItem*, column)'), self.onClick)

    def onClick(self, item, column):

        print item

class MainWindow(QMainWindow):

    def __init__(self, parent = None):

        super(MainWindow, self).__init__(parent)
        self.tree = MyTree(self)

def main():

    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    app.exec_()

if __name__ == '__main__':
    main()

我最初的目标是让 MyTree.onClick() 在我点击一个树项目时打印一些东西(并且可以在这个处理程序中访问被点击的项目).

My initial goal is to make MyTree.onClick() print something when I click a tree item (and have access to the clicked item in this handler).

推荐答案

你应该说

self.connect(self, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.onClick)

请注意,SIGNAL 的第一个参数中显示的是 int 而不是 column.您还只需为树小部件调用一次 connect 调用,而不是为树中的每个节点调用一次.

Notice it says int rather than column in the first argument to SIGNAL. You also only need to do the connect call once for the tree widget, not once for each node in the tree.

这篇关于PyQt:事件未触发,我的代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆