- PyQt - QPixmap Class
- PyQt - QClipboard
- PyQt - BrushStyle Constants
- PyQt - Drawing API
- PyQt - Database Handling
- PyQt - Drag and Drop
- PyQt - Multiple Document Interface
- PyQt - QMessageBox
- PyQt - QDialog Class
- PyQt - Basic Widgets
- PyQt - Layout Management
- PyQt - Signals and Slots
- PyQt - Using Qt Designer
- PyQt - Major Classes
- PyQt - Hello World
- PyQt - Introduction
- PyQt - Home
PyQt Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
PyQt - Signals & Slots
Unpke a console mode apppcation, which is executed in a sequential manner, a GUI based apppcation is event driven. Functions or methods are executed in response to user’s actions pke cpcking on a button, selecting an item from a collection or a mouse cpck etc., called events.
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.
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)
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)
Suppose if a function is to be called when a button is cpcked. Here, the cpcked 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(“cpcked()”), slot_function)
or
button.cpcked.connect(slot_function)
Example
In the following example, two QPushButton objects (b1 and b2) are added in QDialog window. We want to call functions b1_cpcked() and b2_cpcked() on cpcking b1 and b2 respectively.
When b1 is cpcked, the cpcked() signal is connected to b1_cpcked() function
b1.cpcked.connect(b1_cpcked())
When b2 is cpcked, the cpcked() signal is connected to b2_cpcked() function
QObject.connect(b2, SIGNAL("cpcked()"), b2_cpcked)
Example
import sys from PyQt4.QtCore import * from PyQt4.QtGui import * def window(): app = QApppcation(sys.argv) win = QDialog() b1 = QPushButton(win) b1.setText("Button1") b1.move(50,20) b1.cpcked.connect(b1_cpcked) b2 = QPushButton(win) b2.setText("Button2") b2.move(50,50) QObject.connect(b2,SIGNAL("cpcked()"),b2_cpcked) win.setGeometry(100,100,200,100) win.setWindowTitle("PyQt") win.show() sys.exit(app.exec_()) def b1_cpcked(): print "Button 1 cpcked" def b2_cpcked(): print "Button 2 cpcked" if __name__ == __main__ : window()
The above code produces the following output −
Output
Button 1 cpcked Button 2 cpckedAdvertisements