您的位置:首页 > 编程语言 > Qt开发

PyQt4的事件与信号

2013-10-11 13:24 399 查看
PyQt4的事件与信号

事件(event)

事件由用户或者系统产生,当我们调用程序的exec_()方法时,程序进入主循环中。主循环就会捕捉事件并将它们发送给相应的对象进行处理。

信号与槽

其实信号和槽就是方法

当我们点击某个按钮,或者某个控件有动作,都会发送相应的信号。

信号可以自定义 利用 sender.emit(QtCore.SIGNAL("xxx自定义的信号"),receiver)

链接信号与槽的方法connect

PyQt4中对connect方法的申明有三种:

1、第一种:

bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection ) [static]

有5个参数:

QObject * sender----信号的发送者对象

char * signal-----------要发送的信号 QtCore.SIGNAL(‘发送的信号’)

QObject * receiver---信号接收者对象

char * method---------对信号做出响应的函数

Qt::ConnectionType—表示信号发送个槽的方式默认是AutoConnection

如果成功返回true;

帮助文档的例子

A.
connect(scrollBar, SIGNAL(valueChanged(int)),label, SLOT(setNum(int))) scrollBar发送valueChanged(int)信号给label,label执行setNum(int)方法

B. connect(myButton, SIGNAL(clicked()), this, SIGNAL(buttonClicked()))即一个信号也可以传递给另一个信

2.第二种:

bool QObject::connect ( const QObject * sender, const QMetaMethod & signal, const QObject * receiver, const QMetaMethod & method, Qt::ConnectionType type = Qt::AutoConnection ) [static]

和第一种用法一样,只是用QMetaMethod来表示信号和方法

第三种:

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

等价于connect(sender, signal, this, method, type)

一般你只需要传递(sender,signal,method)即可

一个简单实例

# -*- coding: utf-8 -*-

from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

def __init__(self, parent=None):

QtGui.QWidget.__init__(self, parent)

self.setGeometry(300, 300, 400, 300)

self.setWindowTitle("exmaple")

okbutton=QtGui.QPushButton('ok', self)

okbutton.move(10, 10)

self.connect(okbutton, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()'))

if __name__ == "__main__":

import sys

app = QtGui.QApplication(sys.argv)

dialog = Example()

dialog.show()

sys.exit(app.exec_())



点击ok按钮,发出clicked()信号,对话框quit()槽响应退出

这些都是老式的形式,新式的API还没有学习,路漫漫其修远兮。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: