Pyqt 简明教程
PyQt - Signals & Slots
与按顺序执行的控制台模式应用程序不同,基于 GUI 的应用程序是事件驱动的。函数或方法会执行响应用户的操作,例如单击按钮、从集合中选择一个项目,或鼠标单击等,称为 events 。
Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking on a button, selecting an item from a collection or a mouse click etc., called events.
用于构建 GUI 界面的小组件充当此类事件的源。PyQt 中的每个小组件(派生自 QObject 类)都设计为针对一个或多个事件发出“ signal ”。信号本身不执行任何操作。相反,信号被“连接”到“ slot ”。槽可以是任何 callable Python function 。
Widgets used to build the GUI interface act as the source of such events. Each PyQt widget, which is derived from QObject class, is designed to emit ‘signal’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a ‘slot’. The slot can be any callable Python function.
在 PyQt 中,信号与槽之间的连接可以通过多种方式实现。以下是最常用的技术 −
In PyQt, connection between a signal and a slot can be achieved in different ways. Following are most commonly used techniques −
QtCore.QObject.connect(widget, QtCore.SIGNAL(‘signalname’), slot_function)
在小组件发出信号时调用 slot_function 的更便捷的方式如下 −
A more convenient way to call a slot_function, when a signal is emitted by a widget is as follows −
widget.signal.connect(slot_function)
假设在单击按钮时调用某个函数。此处,clicked 信号应连接到可调用函数。可以通过以下两种技术中的任何一种来实现:
Suppose if a function is to be called when a button is clicked. Here, the clicked signal is to be connected to a callable function. It can be achieved in any of the following two techniques −
QtCore.QObject.connect(button, QtCore.SIGNAL(“clicked()”), slot_function)
或
or
button.clicked.connect(slot_function)
Example
在以下示例中,两个 QPushButton 对象(b1 和 b2)添加到 QDialog 窗口中。我们希望分别在单击 b1 和 b2 时调用函数 b1_clicked() 和 b2_clicked()。
In the following example, two QPushButton objects (b1 and b2) are added in QDialog window. We want to call functions b1_clicked() and b2_clicked() on clicking b1 and b2 respectively.
当单击 b1 时,clicked() 信号连接到 b1_clicked() 函数
When b1 is clicked, the clicked() signal is connected to b1_clicked() function
b1.clicked.connect(b1_clicked())
当单击 b2 时,clicked() 信号连接到 b2_clicked() 函数
When b2 is clicked, the clicked() signal is connected to b2_clicked() function
QObject.connect(b2, SIGNAL("clicked()"), b2_clicked)
Example
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def window():
app = QApplication(sys.argv)
win = QDialog()
b1 = QPushButton(win)
b1.setText("Button1")
b1.move(50,20)
b1.clicked.connect(b1_clicked)
b2 = QPushButton(win)
b2.setText("Button2")
b2.move(50,50)
QObject.connect(b2,SIGNAL("clicked()"),b2_clicked)
win.setGeometry(100,100,200,100)
win.setWindowTitle("PyQt")
win.show()
sys.exit(app.exec_())
def b1_clicked():
print "Button 1 clicked"
def b2_clicked():
print "Button 2 clicked"
if __name__ == '__main__':
window()
上述代码生成以下输出 -
The above code produces the following output −