事件是任何 GUI 程序中很重要的部分。所有 GUI 应用都是事件驱动的。一个应用对其生命期产生的不同的事件类型做出反应。事件是主要由应用的用户产生。但是,也可以通过其他方法产生,比如,网络通信,窗口的管理者,计时器。
PyQt 4.5 引入了新的 API 用于信号和槽。
这是旧式的 API 。
QtCore.QObject.connect(self.ui.button_open,QtCore.SIGNAL("clicked()"), self.file_dialog)
新式的更接近 Python 的标准
button.clicked.connect(self.onClicked)
self.ui对应窗口,通过它我们可以访问窗口中的部件。因此,self.ui.button_open对应“打开”按钮。self.file_dialog是信号对应的函数,它是比较重要的部分。
test.py测试代码:
import sysfrom PyQt4 import QtCore, QtGuifrom ui_test import Ui_notepadclass MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_notepad() self.ui.setupUi(self) # here we connect signals with our slots QtCore.QObject.connect(self.ui.button_open,QtCore.SIGNAL("clicked()"), self.file_dialog) def file_dialog(self): #self.ui.editor_window.setText('aaaaaaaaaa') fd = QtGui.QFileDialog(self) self.filename = fd.getOpenFileName() from os.path import isfile if isfile(self.filename): text = open(self.filename).read() self.ui.editor_window.setText(text) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyForm() myapp.show() sys.exit(app.exec_())
ui_test.py UI生成代码:
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'test.ui'## Created: Sat Jan 11 22:11:39 2014# by: PyQt4 UI code generator 4.10.3## WARNING! All changes made in this file will be lost!from PyQt4 import QtCore, QtGuitry: _fromUtf8 = QtCore.QString.fromUtf8except AttributeError: def _fromUtf8(s): return stry: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding)except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig)class Ui_notepad(object): def setupUi(self, notepad): notepad.setObjectName(_fromUtf8("notepad")) notepad.resize(692, 462) self.button_open = QtGui.QPushButton(notepad) self.button_open.setGeometry(QtCore.QRect(60, 10, 75, 23)) self.button_open.setObjectName(_fromUtf8("button_open")) self.button_close = QtGui.QPushButton(notepad) self.button_close.setGeometry(QtCore.QRect(290, 10, 75, 23)) self.button_close.setObjectName(_fromUtf8("button_close")) self.editor_window = QtGui.QTextEdit(notepad) self.editor_window.setGeometry(QtCore.QRect(20, 50, 651, 381)) self.editor_window.setObjectName(_fromUtf8("editor_window")) self.button_save = QtGui.QPushButton(notepad) self.button_save.setGeometry(QtCore.QRect(180, 10, 75, 23)) self.button_save.setObjectName(_fromUtf8("button_save")) self.retranslateUi(notepad) QtCore.QObject.connect(self.button_close, QtCore.SIGNAL(_fromUtf8("clicked()")), notepad.close) QtCore.QMetaObject.connectSlotsByName(notepad) def retranslateUi(self, notepad): notepad.setWindowTitle(_translate("notepad", "Form", None)) self.button_open.setText(_translate("notepad", "打开", None)) self.button_close.setText(_translate("notepad", "关闭", None)) self.button_save.setText(_translate("notepad", "保存", None))