码迷,mamicode.com
首页 > 其他好文 > 详细

自定义信号与槽

时间:2018-10-16 17:51:22      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:which   处理   nts   设置   hang   required   ISE   enabled   finish   

引自:《PyQt5官网Doc:Support for Signals and Slots》《Qt5官网: Signals & Slots

 

Qt 对于大部分widget的常规操作,都预定义了一系列的 connect(),例如你按下一个按钮,至于动作的实现,只需要重写 On_Click_Button() 就能实现。这个过程就包括了内在的信号-槽连接。而这些关联动作已经在基类中配置好了,故而你不需要指定connect也可以实现动作。

但如果我们需要自定义一些信号和槽的连接动作呢?

The signal/slot mechanism has the following features.

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

技术分享图片

 

解读信号

A signal (specifically an unbound signal) is a class attribute. When a signal is referenced as an attribute of an instance of the class then PyQt5 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 signal attribute that is the signature of the signal that would be returned by Qt’s SIGNAL() macro.

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. The name of a C++ type is automatically normalised so that, for example, QVariant can be used instead of the non-normalised const QVariant &.

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.

关于信号,我们来品味下C++版本的定义:

Signals are automatically generated by the moc and must not be implemented in the .cpp file. They can never have return types (i.e. use void).

#include <QObject>

class Counter : public QObject
{
    Q_OBJECT

public:
    Counter() { m_value = 0; }

    int value() const { return m_value; }

public slots:
    void setValue(int value);

signals:
    void valueChanged(int newValue);

private:
    int m_value;
};

Defining New Signals with pyqtSignal()

PyQt5.QtCore.pyqtSignal(types[, name[, revision=0[, arguments=[]]]])

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

from PyQt5.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. They must be part of the class definition and cannot be dynamically added as class attributes after the class has been defined.

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.

由于Python的默认数据类型与C++不同,故增加了一些限制,例如:

class Foo(QObject):

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

Connecting, Disconnecting and Emitting Signals

最原始的方式是 QObject::connect():【静态函数】

QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)

QMetaObject::Connection QObject::connect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type = Qt::AutoConnection)

……  // 这个重载比较多,总之第一个参数一定是 sender,第二个是 signal 对象。

其使用方式如下:

self.connect(self.myButton, QtCore.SIGNAL(clicked()), self.slot_func)

这个方式并不容易控制参数的传递……

@pyqtSlot 信号连接

对于 @pyqtSlot 修饰的信号,可以直接链接槽函数,常用方法包括以下三种:

signal_obj.connect(slot[, type=PyQt5.QtCore.Qt.AutoConnection[, no_receiver_check=False]]) → PyQt5.QtCore.QMetaObject.Connection

signal_obj.disconnect([slot])

signal_obj.emit(*args)

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

from PyQt5.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 PyQt5.QtWidgets import QComboBox

class Bar(QComboBox):

    def connect_activated(self):
        # The PyQt5 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. For example the following three fragments are equivalent:

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

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

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

槽函数

PyQt5.QtCore.pyqtSlot(types[, name[, result[, revision=0]]])

Although PyQt5 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. PyQt5 provides the pyqtSlot() function decorator to do this.

The @pyqtSlot Decorator

Connecting a signal to a decorated Python method also has the advantage of reducing the amount of memory used and is slightly faster. 所以说,使用pyqtSlot 修饰符是一种PyQt5的推荐方案。

from PyQt5.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:

from PyQt5.QtCore import QObject, pyqtSlot

class Foo(QObject):

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

通过Lambda表达式灵活传入slot

由于槽函数的格式限定严格,而往往调用响应函数的方式却很灵活,Lambda提供了一种很方便的表达形式。

def commander (self, arg):
    exec arg    

def aButton (self, layout, **kwargs):
    name = kwargs.pop("name","Button")
    command = kwargs.pop("command", "" )
    button = QtGui.QPushButton(name)
    button.clicked.connect(self.commander(command))

# Error: TypeError: connect() slot argument should be a callable or a signal, not ‘NoneType‘

上述错误的示例,用Lambda表达式处理却很容易:

button.clicked.connect(lambda: self.commander(command))

Connecting Slots By Name

PyQt5 supports the connectSlotsByName() function that is most commonly used by pyuic5 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) PyQt5 needs additional information in order to automatically connect the correct signal.

关于重载(同名)槽函数的多次调用问题

For example the 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 called on_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 string argument.

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

 


 

pyqtSlot方式使用的前提,正是 QMetaObject.connectSlotsByName(QObject) 函数已经被执行。

事实上,它是在PyQt 5中根据信号名称自动连接到槽函数的核心代码。通过前面章节中的例子可以知道,使用pyuic5命令生成的代码中会带有这么一行代码,接下来对其进行解释。

这行代码用来将QObject中的子孙对象的某些信号按照其objectName连接到相应的槽函数。这句话读起来有些拗口,这里举个例子进行简单说明。

@pyqtSlot 修饰的槽函数实际上会被转换为以下格式:

def __init__(self, parent=None):

    self.okButton.clicked.connect(self.okButton_clicked)

    def okButton_clicked(self):
        print("单击了OK按钮")

可以试用以下“原生格式”代码:

from PyQt5 import QtCore 
from PyQt5.QtWidgets import QApplication ,QWidget ,QHBoxLayout , QPushButton
import sys    

class CustWidget( QWidget ):

    def __init__(self, parent=None):
        super(CustWidget, self).__init__(parent)

        self.okButton = QPushButton("OK", self)
        #使用setObjectName设置对象名称
        self.okButton.setObjectName("okButton")        
        layout =  QHBoxLayout()
        layout.addWidget(self.okButton)
        self.setLayout(layout)                
        QtCore.QMetaObject.connectSlotsByName(self)
        self.okButton.clicked.connect(self.okButton_clicked)

    def okButton_clicked(self):
        print( "单击了OK按钮")

if __name__ == "__main__":        
    app =  QApplication(sys.argv)
    win = CustWidget()
    win.show()
    sys.exit(app.exec_())

以上内容引自:《PyQt 5信号与槽的几种高级玩法

The PyQt_PyObject Signal Argument Type

It is possible to pass any Python object as a signal argument by specifying PyQt_PyObject as the type of the argument in the signature. For example:

finished = pyqtSignal(PyQt_PyObject)

This would normally be used for passing objects where the actual Python type isn’t known. It can also be used to pass an integer, for example, so that the normal conversions from a Python object to a C++ integer and back again are not required.

The reference count of the object being passed is maintained automatically. There is no need for the emitter of a signal to keep a reference to the object after the call to finished.emit(), even if a connection is queued.

 


思考

  1. 在PyQt5中,一般的 pyqtSignal 对象需要被定义为类属性。

 

自定义信号与槽

标签:which   处理   nts   设置   hang   required   ISE   enabled   finish   

原文地址:https://www.cnblogs.com/brt3/p/9798011.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!