New-style Signal and Slot Support 简单注释

本文详细介绍了PyQt4中信号与槽机制的新特性,包括信号的定义、连接与断开,以及如何使用装饰器指定槽函数的签名。此外,还探讨了如何处理信号重载,并提供了自动连接信号到槽的示例。

New-style Signal and Slot Support

This section describes the new style of connecting signals and slots introduced in PyQt4 v4.5.

One of the key features of Qt is its use of signals and slots to communicate between objects. Their use encourages the development of reusable components.

A signal is emitted when something of potential interest happens. A slot is a Python callable. If a signal is connected to a slot then the slot is called when the signal is emitted. If a signal isn’t connected then nothing happens. The code (or component) that emits the signal does not know or care if the signal is being used.

The signal/slot mechanism has the following features.

  • A signal may be connected to many slots.
  • A signal may also be connected to another signal.
  • Signal arguments may be any Python type.
  • A slot may be connected to many signals.
  • Connections may be direct (ie. synchronous) or queued (ie. asynchronous).
  • Connections may be made across threads.
  • Signals may be disconnected.

Unbound and Bound Signals

A signal (specifically an unbound signal) is an attribute of a class that is a sub-class of QObject. When a signal is referenced as an attribute of an instance of the class then PyQt4 automatically binds the instance to the signal in order to create a bound signal. This is the same mechanism that Python itself uses to create bound methods from class functions.

A bound signal has connect()disconnect() and emit() methods that implement the associated functionality. It also has a signalattribute that is the signature of the signal that would be returned by Qt’s SIGNAL() macro.

定义成类方法,会自动变成实例方法。从unbound signal变成bound signal,这样它就有了connect()等方法

 

A signal may be overloaded, ie. a signal with a particular name may support more than one signature. A signal may be indexed with a signature in order to select the one required. A signature is a sequence of types. A type is either a Python type object or a string that is the name of a C++ type.

If a signal is overloaded then it will have a default that will be used if no index is given.

When a signal is emitted then any arguments are converted to C++ types if possible. If an argument doesn’t have a corresponding C++ type then it is wrapped in a special C++ type that allows it to be passed around Qt’s meta-type system while ensuring that its reference count is properly maintained.

 

信号可以被重载。signature的概念...,它可以是Python类型或者C++类型(写成字符串),默认.. emit的时候,参数会被转换成C++类型,如果不能正确转换,会Wrap一个..

Defining New Signals with pyqtSignal()

PyQt4 automatically defines signals for all Qt’s built-in signals. New signals can be defined as class attributes using thepyqtSignal() factory.

PyQt4.QtCore.pyqtSignal(types[name])

Create one or more overloaded unbound signals as a class attribute.

Parameters:
  • types – the types that define the C++ signature of the signal.
    Each type may be a Python type object or a string that is the name of a C++ type.
    Alternatively each may be a sequence of type arguments.
    In this case each sequence defines the signature of a different signal overload.

    The first overload will be the default.
  • name – the name of the signal. If it is omitted then the name of the class attribute is used. This may only be given as a keyword argument.
Return type:

an unbound signal

The following example shows the definition of a number of new signals:

from PyQt4.QtCore import QObject, pyqtSignal

class Foo(QObject):

    # This defines a signal called 'closed' that takes no arguments.
    closed = pyqtSignal()

    # This defines a signal called 'rangeChanged' that takes two
    # integer arguments.
    range_changed = pyqtSignal(int, int, name='rangeChanged')

    # This defines a signal called 'valueChanged' that has two overloads,
    # one that takes an integer argument and one that takes a QString
    # argument.  Note that because we use a string to specify the type of
    # the QString argument then this code will run under Python v2 and v3.
    valueChanged = pyqtSignal([int], ['QString'])

New signals should only be defined in sub-classes of QObject.

New signals defined in this way will be automatically added to the class’s QMetaObject. This means that they will appear in Qt Designer and can be introspected using the QMetaObject API.

Overloaded signals should be used with care when an argument has a Python type that has no corresponding C++ type. PyQt4 uses the same internal C++ class to represent such objects and so it is possible to have overloaded signals with different Python signatures that are implemented with identical C++ signatures with unexpected results. The following is an example of this:

Python类型会转换成C++类型,有些类型转换成C++类型后是一样的,比如下面这个:

 

class Foo(QObject):

    # This will cause problems because each has the same C++ signature.
    valueChanged = pyqtSignal([dict], [list])

Connecting, Disconnecting and Emitting Signals

Signals are connected to slots using the connect() method of a bound signal.

connect ( slot [type=PyQt4.QtCore.Qt.AutoConnection ] )

Connect a signal to a slot. An exception will be raised if the connection failed.

Parameters:
  • slot – the slot to connect to, either a Python callable or another bound signal.
  • type – the type of the connection to make.

Signals are disconnected from slots using the disconnect() method of a bound signal.

disconnect ( [ slot ] )

Disconnect one or more slots from a signal. An exception will be raised if the slot is not connected to the signal or if the signal has no connections at all.

Parameters: slot – the optional slot to disconnect from, either a Python callable or another bound signal. If it is omitted then all slots connected to the signal are disconnected.

Signals are emitted from using the emit() method of a bound signal.

emit ( *args )

Emit a signal.

Parameters: args – the optional sequence of arguments to pass to any connected slots.

The following code demonstrates the definition, connection and emit of a signal without arguments:

from PyQt4.QtCore import QObject, pyqtSignal

class Foo(QObject):

    # Define a new signal called 'trigger' that has no arguments.
    trigger = pyqtSignal()

    def connect_and_emit_trigger(self):
        # Connect the trigger signal to a slot.
        self.trigger.connect(self.handle_trigger)

        # Emit the signal.
        self.trigger.emit()

    def handle_trigger(self):
        # Show that the slot has been called.

        print "trigger signal received"

The following code demonstrates the connection of overloaded signals:

注意重载信号的写法:

from PyQt4.QtGui import QComboBox

class Bar(QComboBox):

    def connect_activated(self):
        # The PyQt4 documentation will define what the default overload is.
        # In this case it is the overload with the single integer argument.
        self.activated.connect(self.handle_int)

        # For non-default overloads we have to specify which we want to
        # connect.  In this case the one with the single string argument.
        # (Note that we could also explicitly specify the default if we
        # wanted to.)
        self.activated[str].connect(self.handle_string)

    def handle_int(self, index):
        print "activated signal passed integer", index

    def handle_string(self, text):
        print "activated signal passed QString", text

Connecting Signals Using Keyword Arguments

It is also possible to connect signals by passing a slot as a keyword argument corresponding to the name of the signal when creating an object, or using the pyqtConfigure() method of QObject. For example the following three fragments are equivalent:

几个函数的用法:

act = QtGui.QAction("Action", self)
act.triggered.connect(self.on_triggered)

act = QtGui.QAction("Action", self, triggered=self.on_triggered)

act = QtGui.QAction("Action", self)
act.pyqtConfigure(triggered=self.on_triggered)

The pyqtSlot() Decorator

Although PyQt4 allows any Python callable to be used as a slot when connecting signals, it is sometimes necessary to explicitly mark a Python method as being a Qt slot and to provide a C++ signature for it. PyQt4 provides the pyqtSlot() function decorator to do this.

PyQt4.QtCore.pyqtSlot(types[, name][, result])

Decorate a Python method to create a Qt slot.

Parameters:
  • types – the types that define the C++ signature of the slot. Each type may be a Python type object or a string that is the name of a C++ type.
  • name – the name of the slot that will be seen by C++. If omitted the name of the Python method being decorated will be used. This may only be given as a keyword argument.
  • result – the type of the result and may be a Python type object or a string that specifies a C++ type. This may only be given as a keyword argument.

Connecting a signal to a decorated Python method also has the advantage of reducing the amount of memory used and is slightly faster.

@pyqtSlot可以定义类型,名字和返回的类型。

 

For example:

from PyQt4.QtCore import QObject, pyqtSlot

class Foo(QObject):

    @pyqtSlot()
    def foo(self):
        """ C++: void foo() """

    @pyqtSlot(int, str)
    def foo(self, arg1, arg2):
        """ C++: void foo(int, QString) """

    @pyqtSlot(int, name='bar')
    def foo(self, arg1):
        """ C++: void bar(int) """

    @pyqtSlot(int, result=int)
    def foo(self, arg1):
        """ C++: int foo(int) """

    @pyqtSlot(int, QObject)
    def foo(self, arg1):
        """ C++: int foo(int, QObject *) """

It is also possible to chain the decorators in order to define a Python method several times with different signatures. For example:

可以有多个@pyqtSlot

from PyQt4.QtCore import QObject, pyqtSlot

class Foo(QObject):

    @pyqtSlot(int)
    @pyqtSlot('QString')
    def valueChanged(self, value):
        """ Two slots will be defined in the QMetaObject. """

Connecting Slots By Name

PyQt4 supports the QtCore.QMetaObject.connectSlotsByName() function that is most commonly used by pyuic4 generated Python code to automatically connect signals to slots that conform to a simple naming convention. However, where a class has overloaded Qt signals (ie. with the same name but with different arguments) PyQt4 needs additional information in order to automatically connect the correct signal.

 

QtCore.QMetaObject.connectSlotsByName()函数会把信号和Slots自动关联起来,按照这样的命名:

 

 void on_<object name>_<signal name>(<signal parameters>);

 

比如:QPushButton with the object name button1. The slot to catch the button's clicked() signal would be:

 

 void on_button1_clicked();

 

所以,下面的例子会关联两次:on_spinbox_valueChanged(),用@pyqtslot就可以正常处理

 

For example the QtGui.QSpinBox class has the following signals:

void valueChanged(int i);
void valueChanged(const QString &text);

When the value of the spin box changes both of these signals will be emitted. If you have implemented a slot calledon_spinbox_valueChanged (which assumes that you have given the QSpinBox instance the name spinbox) then it will be connected to both variations of the signal. Therefore, when the user changes the value, your slot will be called twice - once with an integer argument, and once with a unicode or QString argument.

This also happens with signals that take optional arguments. Qt implements this using multiple signals. For example,QtGui.QAbstractButton has the following signal:

void clicked(bool checked = false);

Qt implements this as the following:

void clicked();
void clicked(bool checked);

The pyqtSlot() decorator can be used to specify which of the signals should be connected to the slot.

For example, if you were only interested in the integer variant of the signal then your slot definition would look like the following:

@pyqtSlot(int)
def on_spinbox_valueChanged(self, i):
    # i will be an integer.
    pass

If you wanted to handle both variants of the signal, but with different Python methods, then your slot definitions might look like the following:

@pyqtSlot(int, name='on_spinbox_valueChanged')
def spinbox_int_value(self, i):
    # i will be an integer.
    pass

@pyqtSlot(str, name='on_spinbox_valueChanged')
def spinbox_qstring_value(self, s):
    # s will be a Python string object (or a QString if they are enabled).
    pass

The following shows an example using a button when you are not interested in the optional argument:

@pyqtSlot()
def on_button_clicked(self):
    pass

Mixing New-style and Old-style Connections

The implementation of new-style connections is slightly different to the implementation of old-style connections. An application can freely use both styles subject to the restriction that any individual new-style connection should only be disconnected using the new style. Similarly any individual old-style connection should only be disconnected using the old style.

You should also be aware that pyuic4 generates code that uses old-style connections.

<think>好的,用户遇到了“Signal and slot arguments are not compatible”的错误,需要我来帮忙解决。首先,我得回忆一下Qt的信号与槽机制。信号和槽的参数必须匹配,否则就会出现这个错误。 用户之前的代码中,SearchableList类的openProjects信号带有一个QStringList参数,而连接的时候槽函数可能没有正确接收这个参数。比如,在connect语句里,用户可能用了lambda表达式,但参数列表没写对。 接下来,我需要检查用户提供的代码片段。用户给出的代码是: connect(searchWidget, SIGNAL(openProjects(const QStringList&)), [=]() { }); 这里的问题很明显,SIGNAL宏里用了const QStringList&,而槽函数是一个没有参数的lambda。Qt的信号槽机制要求参数类型和数量必须一致。所以当信号发出时,会传递一个QStringList,但lambda没有参数,导致不兼容。 解决办法有两种:要么修改lambda以接收参数,要么使用Qt5的新语法(使用函数指针),这样编译器可以在编译时检查参数是否匹配,避免运行时错误。 用户可能不太熟悉Qt5的新connect语法,所以需要给出示例。例如,将SIGNAL(...)改为&SearchableList::openProjects,并在lambda中添加参数列表。同时,需要确保lambda的参数类型与信号参数一致。 另外,用户可能在使用旧的SIGNAL/SLOT宏时,参数类型写错了,比如遗漏了引用符号或类型不一致。比如,如果信号的参数是QStringList,而槽函数期望的是QString,就会出错。这时候需要检查信号和槽的参数是否完全匹配。 还需要考虑是否在connect时正确传递了参数。比如,使用Qt5的新语法可以更安全,因为编译器会进行类型检查,而旧语法在运行时才会报错。 可能用户没有在SearchableList类中正确声明信号的参数类型,或者槽函数的参数与信号不一致。例如,信号可能发送的是const QStringList&,而槽函数接收的是QStringList,虽然这在C++中可以自动转换,但Qt的元对象系统可能无法正确处理,导致参数不匹配。 总结一下,解决方案应该是: 1. 使用Qt5的connect语法,确保编译时检查。 2. 确保lambda或槽函数的参数与信号参数类型一致。 3. 如果使用旧语法,确保SIGNALSLOT中的参数类型正确且完全匹配。 然后,我需要将这些步骤详细说明,并提供修改后的代码示例,指出用户哪里出错了,以及如何修正。同时,可能还需要解释为什么旧代码有问题,以及新方法的优势。 最后,生成相关的后续问题,帮助用户深入理解,比如参数类型转换、使用lambda表达式捕获变量,以及调试信号槽连接的其他技巧。</think>在Qt中出现"Signal and slot arguments are not compatible"错误的根本原因是信号与槽的参数类型/数量不匹配。以下是针对您代码的具体修复方案: ```cpp // 正确的连接方式(使用Qt5新语法): connect(searchWidget, &SearchableList::openProjects, [=](const QStringList& items){ qDebug() << "收到项目列表:" << items; }); ``` **错误分析**: 1. 原代码使用了旧式SIGNAL/SLOT宏: ```cpp connect(searchWidget, SIGNAL(openProjects(const QStringList&)), [=]() {}); ``` - 问题1:SIGNAL宏不处理参数类型检查 - 问题2:lambda表达式没有声明接收参数 - 问题3:引用符号(&)可能导致元对象解析错误 2. 参数匹配规则要求: | 信号参数类型 | 槽函数参数类型 | 兼容性 | |-----------------------|-------------------------|--------| | const T& | T | ✅ | | T | const T& | ✅ | | T* | T* | ✅ | | QList<T> | QVector<T> | ❌ | **完整修复方案**: ```cpp // SearchableList.h class SearchableList : public QWidget { Q_OBJECT signals: void openProjects(const QStringList& items); // 信号声明 }; // 使用处(正确连接) SearchableList* searchWidget = new SearchableList(); connect(searchWidget, &SearchableList::openProjects, this, [=](const QStringList& items){ // 显式声明参数 // 处理逻辑 qDebug() << "选中项目数:" << items.size(); } ); ``` **进阶调试技巧**: 1. 使用`QMetaObject::connectSlotsByName()`自动连接时: ```cpp // 需要确保: // 1. 槽函数命名规范:on_<控件名>_<信号名> // 2. 参数类型完全匹配 void on_searchWidget_openProjects(const QStringList& items); ``` 2. 参数类型转换失败示例: ```cpp // 错误:QStringList -> QString 类型不兼容 connect(searchWidget, &SearchableList::openProjects, [](const QString& item){}); // ❌ 编译失败 ``` 3. 使用`QSignalMapper`进行参数映射(Qt5.10以下): ```cpp QSignalMapper* mapper = new QSignalMapper(this); connect(searchWidget, &SearchableList::openProjects, mapper, &QSignalMapper::map); mapper->setMapping(searchWidget, "custom_arg"); connect(mapper, static_cast<void(QSignalMapper::*)(const QString&)>(&QSignalMapper::mapped), [=](const QString& arg){ /* 处理映射后的参数 */ }); ``` **最佳实践**: 1. 优先使用Qt5的函数指针语法(编译时检查) 2. 参数类型保持const &传递效率 3. 使用`QMetaObject::Connection`管理连接状态: ```cpp QMetaObject::Connection conn = connect(...); disconnect(conn); // 安全断开连接 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值