0

当我想创建一个 QAction 时,我创建了这个对象。然后我将此 QAction 添加到菜单中:

class ActionObject(object):
  def __init__(self, owner, command):
    action = QtGui.QAction(command.name, owner)
    self.action = action
    self.command = command
    action.setShortcut(command.shortcut)
    action.setStatusTip(command.name)
    QtCore.QObject.connect(action, QtCore.SIGNAL('triggered()'), self.triggered)
  def triggered(self):
    print("got triggered " + self.command.id + " " + repr(checked))

Unfortunately, when the menu item is selected, the 'triggered' function is not called. QtCore.QObject.connect() 返回 True。控制台上没有打印任何内容以指示任何错误,并且不会引发异常。

我该如何调试呢?(或者,我做错了什么?)

4

4 回答 4

1

也许有点晚了,但我遇到了同样的问题,我通过改变 class ActionObject(object) 来 解决它:class ActionObject()

于 2010-12-08T17:00:00.807 回答
0

我没有看到您action在此代码中添加到任何菜单(实际上我在任何地方都没有看到任何调用),并且有一个从未在您的方法中任何地方定义addAction的变量的特殊用途(它是在其他地方定义的全局变量吗?)。这两个问题都表明您还有其他未显示的代码(将此操作添加到某些菜单或工具栏并定义全局变量的代码- 或者您是否在语句中省略了参数,也许......?) ,这就是错误所在(此代码是可能正确程序的子集......但显然有缺失的部分,我们怎么知道它们是正确的?-)。checkedtriggeredcheckeddef triggered

于 2010-04-21T01:50:17.540 回答
0

看起来您的调试必须在您不提供的两个类之一中进行;您将属性附加到它们,然后将它们作为参数传递给 ActionObject。

我创建了一个没有这个的例子,因为我不知道你的其他两个类是什么样的。第三个,父类,我不需要,因为当然可以是任何继承了QWidget/QMainWindow/QDialog等的泛型类

class ActionObject(object):
  def __init__(self, owner=None, command=None):
    self.menuBar = QtGui.QMenuBar(self)
    self.setMenuBar(self.menuBar)
    # Make sure the menu item's parent is the menu
    self.menuGeneric = QtGui.QMenu(self.menuBar)
    self.menuGeneric.setTitle('&Generic')
    # Create and add the action in one line
    self.menuBar.addAction(self.menuGeneric.menuAction())
    QtCore.QObject.connect(self.menuGeneric, qc.SIGNAL('triggered()'), self.triggered)
  def triggered(self):
    print "got triggered"
于 2010-09-06T02:23:38.853 回答
0

对于你的两个问题:

1)我该如何调试?

1)我要尝试的第一件事是查看您的函数的参数声明是否错误(您有)。为此,我将*argsand添加**kwargs到您的函数中,然后运行代码以查看它是否有效:

def triggered(self, *args, **kwargs):
    print("got triggered " + self.command.id + " " + repr(checked) + " [extra args: {}, kwargs: {}".format(args, kwargs))

我打赌你会发现你得到一个布尔值作为函数的第一个参数,但是你的函数被声明为不接受任何参数。异常可能被记录到 stderr 或被吞下。

2)为了方便起见,我创建了一个简单的装饰器来记录这些类型的东西:

import functools, sys
def logged_action(func):
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        sys.stderr.write("{}: {}, {}\n".format(func, args, kwargs))
        return func(*args, **kwargs)
    return wrapped

@logged_action
def triggered(self, *args, **kwargs):
    print("got triggered " + self.command.id + " " + repr(checked))

2)(或者,我做错了什么)

根据我必须提供的示例的经验,您的连接方法没有正确的签名:

Traceback (most recent call last):
  File "[redacted]", line 12, in wrapped
    return func(*args, **kwargs)
TypeError: triggered() takes exactly 1 argument (2 given)

triggered被 self 和另一个参数调用(因此“给定 2”),但你只是声明你接受一个。

于 2014-07-29T17:14:41.850 回答