Редактирование: PyQt FAQ Events and Signals

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск
Внимание: Вы не представились системе. Ваш IP-адрес будет записан в историю изменений этой страницы.
Правка может быть отменена. Пожалуйста, просмотрите сравнение версий, чтобы убедиться, что это именно те изменения, которые вас интересуют, и нажмите «Записать страницу», чтобы изменения вступили в силу.
Текущая версия Ваш текст
Строка 1: Строка 1:
 +
In this part of the PyQt4 programming tutorial, we will explore events and singnals occuring in applications.
 +
== Events ==
 +
Events are an important part in any GUI program. Events are generated by users or by the system. When we call the application's <i>exec_()</i> method, the application enters the main loop. The main loop fetches events and sends them to the objects. Trolltech has introduced a unique signal and slot mechanism.
 +
 +
== Signals &amp; Slots ==
 +
Signals are emitted, when users click on the button, drag a slider etc. Signals can be emitted also by the environment. For example, when a clock ticks. A slot is a method, that reacts to a signal. In python, a slot can be any python callable.
 +
<source lang="python">
 +
#!/usr/bin/python
 +
 +
# sigslot.py
 +
 +
import sys
 +
from PyQt4 import QtGui, QtCore
 +
 +
 +
class SigSlot(QtGui.QWidget):
 +
    def __init__(self, parent=None):
 +
        QtGui.QWidget.__init__(self, parent)
 +
 +
        self.setWindowTitle('signal & slot')
 +
 +
        lcd = QtGui.QLCDNumber(self)
 +
        slider = QtGui.QSlider(QtCore.Qt.Horizontal, self)
 +
 +
        vbox = QtGui.QVBoxLayout()
 +
        vbox.addWidget(lcd)
 +
        vbox.addWidget(slider)
 +
 +
        self.setLayout(vbox)
 +
        self.connect(slider,  QtCore.SIGNAL('valueChanged(int)'), lcd,
 +
QtCore.SLOT('display(int)') )
 +
 +
        self.resize(250, 150)
 +
 +
 +
app = QtGui.QApplication(sys.argv)
 +
qb = SigSlot()
 +
qb.show()
 +
sys.exit(app.exec_())
 +
</source>
 +
 +
In our example, we display an lcd number and a slider. We change the lcd number by dragging the slider.
 +
 +
<source lang="python">
 +
self.connect(slider,  QtCore.SIGNAL('valueChanged(int)'), lcd, QtCore.SLOT('display(int)') )
 +
</source>
 +
 +
Here we connect a <i>valueChanged()</i> signal of the slider to the <i>display()</i> slot of the lcd number.
 +
 +
The connect method has four parameters. The <b>sender</b> is an object that sends a signal. The <b>signal</b> is the signal, which is emitted. The <b>receiver</b> is the object, that receives the signal. Finally the <b>slot</b> is the method, that reacts to the signal.
 +
 +
[[image: pyqt_faq_signalslot.jpg | center]]
 +
 +
== Reimplementing event handler ==
 +
Events in PyQt are processed mainly by reimplementing event handlers .
 +
<source lang="python">
 +
#!/usr/bin/python
 +
 +
# escape.py
 +
 +
import sys
 +
from PyQt4 import QtGui, QtCore
 +
 +
class Escape(QtGui.QWidget):
 +
    def __init__(self, parent=None):
 +
        QtGui.QWidget.__init__(self, parent)
 +
 +
        self.setWindowTitle('escape')
 +
        self.resize(250, 150)
 +
        self.connect(self, QtCore.SIGNAL('closeEmitApp()'), QtCore.SLOT('close()') )
 +
 +
 +
    def keyPressEvent(self, event):
 +
        if event.key() == QtCore.Qt.Key_Escape:
 +
            self.close()
 +
 +
app = QtGui.QApplication(sys.argv)
 +
qb = Escape()
 +
qb.show()
 +
sys.exit(app.exec_())
 +
</source>
 +
 +
In our example, we reimplement the <i>keyPressEvent()</i> event handler.
 +
 +
<source lang="python">
 +
def keyPressEvent(self, event):
 +
    if event.key() == QtCore.Qt.Key_Escape:
 +
        self.close()
 +
</source>
 +
If we click the escape button, we close the application.
 +
 +
== Emitting signals ==
 +
Objects created from <i>QtCore.QObject</i> can emit signals.
 +
If we click on the button, a clicked() signal is generated. In the following example we will see, how we can emit signals.
 +
 +
<source lang="python">
 +
 +
#!/usr/bin/python
 +
 +
# emit.py
 +
 +
import sys
 +
from PyQt4 import QtGui, QtCore
 +
 +
 +
class Emit(QtGui.QWidget):
 +
    def __init__(self, parent=None):
 +
        QtGui.QWidget.__init__(self, parent)
 +
 +
        self.setWindowTitle('emit')
 +
        self.resize(250, 150)
 +
        self.connect(self, QtCore.SIGNAL('closeEmitApp()'), QtCore.SLOT('close()') )
 +
 +
    def mousePressEvent(self, event):
 +
        self.emit(QtCore.SIGNAL('closeEmitApp()'))
 +
 +
app = QtGui.QApplication(sys.argv)
 +
qb = Emit()
 +
qb.show()
 +
sys.exit(app.exec_())
 +
</source>
 +
 +
We create a new signal called <i>closeEmitApp()</i>. This signal is emitted, during a mouse press event.
 +
 +
<source lang="python">
 +
def mousePressEvent(self, event):
 +
    self.emit(QtCore.SIGNAL('closeEmitApp()'))
 +
</source>
 +
 +
Emitting a signal with the <i>emit()</i> method.
 +
 +
 +
<source lang="python">
 +
self.connect(self, QtCore.SIGNAL('closeEmitApp()'), QtCore.SLOT('close()') )
 +
</source>
 +
 +
Here we connect the manually created <i>closeEmitApp()</i> signal with the <i>close()</i> slot.
 +
 +
[[Категория:Qt]]
 +
[[Категория:Python]]

Пожалуйста, обратите внимание, что все ваши добавления могут быть отредактированы или удалены другими участниками. Если вы не хотите, чтобы кто-либо изменял ваши тексты, не помещайте их сюда.
Вы также подтверждаете, что являетесь автором вносимых дополнений, или скопировали их из источника, допускающего свободное распространение и изменение своего содержимого (см. Wiki.crossplatform.ru:Авторское право). НЕ РАЗМЕЩАЙТЕ БЕЗ РАЗРЕШЕНИЯ ОХРАНЯЕМЫЕ АВТОРСКИМ ПРАВОМ МАТЕРИАЛЫ!