[译]PyQt写代码的好习惯

Posted on 2008-12-01 20:38 美洲豹 阅读(390) 评论(0)  编辑 收藏 引用
 

推荐使用此方法,通过继承QMainWindow达到使界面与代码分离的目的

建立一个新的文件,假设命名为 "test_MyApp.py", 调入如下的代码:

 1# File : test_MyApp.py
 2import sys
 3
 4from PyQt4 import QtGui, QtCore
 5
 6from MyApp import Ui_MainWindow
 7
 8 
 9
10# We start a new class here
11
12# derived from QMainWindow
13
14 
15
16class TestApp(QtGui.QMainWindow):
17
18    def __init__(self):
19
20        QtGui.QMainWindow.__init__(self)
21
22 
23
24        self.ui = Ui_MainWindow()
25
26        self.ui.setupUi(self)
27
28 
29
30        # Connect the pushButton to a message method.
31
32        self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),message)
33
34 
35
36def message():
37
38    print "Hello, world !\n"
39
40 
41
42if __name__ == "__main__":
43
44    app = QtGui.QApplication(sys.argv)
45
46    window = TestApp()
47
48    window.show()
49
50    sys.exit(app.exec_())
51
52

在20至26行将由QtDesigner生成的python UI模块导入,而在32行中加入自定义的slot,这样以后对按钮响应等消息则放在这个文件中,而对原UI文件的修改与这个响应文件的修改则可以相互独立,因为若写在一块的话,每次修改界面,在生成新的UI 模块的时候会将原有的

代码覆盖掉。 


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


posts - 15, comments - 2, trackbacks - 0, articles - 29

Copyright © 美洲豹