pyQt的信号和槽机制

最近一个项目采用Python加PyQt开发界面,本来代码只要翻译Qt的就好,但是在信号和槽机制上除了点问题,在  Qt中只要声明这signals:的信号就能直接发射,但是在python中可不能声明signals:这样的函数,只好上网去翻,有一篇文章写的确实不错,不过是E文的,看的忒费劲的说,原文见下:

 

原文出自灰狐网

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

For example the QtGui.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 QString argument.

This also happens with signals that take optional arguments. Qt implements this using multiple signals. For example, QtGui.QAbstractButton has the following signal:

void clicked(bool checked = false);

Qt implements this as the following:

void clicked();
void clicked(bool checked);

PyQt includes a Python function decorator that can be used to specify which of the signals should be connected to the slot. The decorator takes a string containing the required signal's signature, excluding the parentheses. If you were only interested in the integer variant of the signal then your slot definition would look like the following:

@QtCore.pyqtSignature("int")
def on_spinbox_valueChanged(self, i):
# i will be an integer.
pass

The following shows an example using a button when you are not interested in the optional argument:

@QtCore.pyqtSignature("")
def on_button_clicked(self):
pass
貌似pyqt的信号不需要声明,只要在需要发射信号的地方调用emit函数就可以了
1 self.emit(QtCore.SIGNAL("signal_test(PyQt_PyObject)"),'success')
就是必须在信号函数中带上一个参数:PyQt_PyObject,而且,发射自定义函数至少要有一个参数,并却最多也就一个参数,我实验两个或不带参数,失败了,
,带多个参数,程序能运行,但回报运行中错误,如果没有参数会包内存错误,那位大侠可以解释一下,
所以emit函数的第二个参数就是必须自带的参数,即使不需要也要带上一个参数,郁闷

 

posted @ 2009-05-21 10:55  firefly_liu  阅读(2622)  评论(0编辑  收藏  举报